学习链接
Promise.all
补充:
// Little known fact: Array.prototype itself is an array:
Array.isArray(Array.prototype); // true
Promise.myAll = promiseArr => {
return new Promise((resolve, reject) => {
if (!promiseArr[Symbol.iterator]) {
throw new TypeError(`${promiseArr} is not iterable`) // 需要iterator接口
}
if (!Array.isArray(promiseArr)) {
promiseArr = Array.from(promiseArr); // 根据 iterator 接口转为数组
}
let result = [], count = 0; // count 记录fulfilled数量
promiseArr.forEach((p, i) => {
Promise.resolve(p).then(res => { // 转为 Promise 对象
count++; // 进入then的回调, fulfilled的实例数加一
result[i] = res;
if (count === promiseArr.length) {
resolve(result);
}
}, err => {
reject(err);
})
})
})
}
测试
const promise1 = Promise.resolve(3);
const promise2 = 42;
const promise3 = new Promise((resolve, reject) => {
setTimeout(resolve, 1000, 'foo');
});
Promise.myAll([promise1, promise2, promise3]).then(val => console.log(val));
// [3, 42, 'foo']
Promise.all([promise1, promise2, promise3]).then(val => console.log(val));
const p1 = new Promise((resolve, reject) => {
resolve('hello');
})
.then(result => result)
.catch(e => e);
const p2 = new Promise((resolve, reject) => {
throw new Error('报错了');
})
.then(result => result)
.catch(e => e);
Promise.myAll([p1, p2])
.then(result => console.log(result))
.catch(e => console.log(e));
// ["hello", Error: 报错了]
Promise.all([p1, p2])
.then(result => console.log(result))
.catch(e => console.log(e));
// 验证 iterator 接口
const p1 = Promise.resolve(3);
const p2 = 42;
const p3 = new Promise((resolve, reject) => {
setTimeout(resolve, 1000, 'foo');
});
const promiseArr = [p1, p2, p3];
let num = 0;
const promiseIterator = {
[Symbol.iterator]() {
return {
next() {
if (num < promiseArr.length) {
return { done: false, value: promiseArr[num++] }
}
return { done: true, value: undefined }
}
}
}
};
// Promise.All(promiseIterator)
// .then(result => console.log(result))
// .catch(e => console.log(e));
// [3, 42, 'foo']
Promise.myAll(promiseIterator)
.then(result => console.log(result))
.catch(e => console.log(e));