Promise.all方法是我们在开发中经常要用到的一个方法,在面试中也频繁被要求实现一个Promise.all方法,所以是必须要掌握的。
手写all方法
Promise.prototype.all = (arr) => {
console.log('my all called');
let result = new Array(arr.length);
let counter = 0;//注意这里通过一个变量取保存它的成功的数量
return new Promise((resolve, reject) => {
arr.forEach(async (item, index) => {
let i = index;
Promice.resolve(item).then(value => {
result[i] = value;
counter ++;
if (counter === arr.length) {//通过conter变量比较,而不是直接通过result.length去判断
resolve(result);
}
}).catch(err => {
reject(err)
})
})
});
}
测试
测试全部是成功的情况:
Promise.all([
new Promise((resolve, reject) => {
setTimeout(() => {
resolve(1);
}, 200)
}),
new Promise((resolve, reject) => {
setTimeout(() => {
resolve(2);
}, 100)
}),
new Promise((resolve, reject) => {
setTimeout(() => {
resolve(3);
}, 400)
}),
new Promise((resolve, reject) => {
setTimeout(() => {
resolve(4);
}, 300)
}),
])
.then(res => console.log('result:', res))
.catch(err => {
console.log('err:', err)
});
//输出: result: [1,2,3,4]
测试存在reject的情况:
Promise.all([
new Promise((resolve, reject) => {
setTimeout(() => {
resolve(1);
}, 200)
}),
new Promise((resolve, reject) => {
setTimeout(() => {
reject(2);
}, 100)
}),
new Promise((resolve, reject) => {
setTimeout(() => {
resolve(3);
}, 400)
}),
new Promise((resolve, reject) => {
setTimeout(() => {
resolve(4);
}, 300)
}),
])
.then(res => console.log('result:', res))
.catch(err => {
console.log('err:', err)
});
//输出:err:2
经测试,达到了预期效果,如有需要改善的地方,欢迎留言。