- 用数组下标的方式保证promise有序
Promise.all = function(arr) {
let results = []
let count = 0
return new Promise((resolve, reject) => {
arr.forEach((p, i) => {
Promise.resolve(p).then(res => {
count++
results[i] = p;
if(count === arr.length) {
resolve(results)
}
}).catch(err => {
reject(err)
})
});
});
}
测试代码
let p1 = 1;
let p2 = new Promise((resolve) => {
setTimeout(() => {
resolve(2)
}, 2000)
});
let p3 = new Promise((resolve) => {
setTimeout(() => {
resolve(3)
}, 1000)
});
let p4 = Promise.reject(4)
let res1 = Promise.all([p1, p2, p3])
let res2 = Promise.all([p1, p2, p4])
res1.then(res => {
console.log(res)
// 1 promise2 promise3
}
res2.then(res => {
console.log(res)
}).catch(err => {
console.log(err)
// 4
})