let p1 = new Promise((resolve, reject)=>{
setTimeout(()=> {
resolve(1111)
}, 2000)
});
let p2 = new Promise((resolve, reject)=>{
setTimeout(()=> {
resolve(2222)
}, 1000)
});
// 实现 Promise.all() 方法
function myPromiseAll(list) {
return new Promise((resolve, reject) => {
let resAll = [];
let num = 0;
list.forEach(item=> {
item.then(res=>{
resAll.push(res);
num++;
if(num === list.length) {
resolve(resAll)
}
})
})
});
}
// 只有当 promise 触发resolve的时候才会返回触发.then(res=>{})
myPromiseAll([p1, p2]).then(res=>{
console.log(res)
})
手写代码实现一个Promise.all()方法
最新推荐文章于 2024-07-26 16:51:17 发布