// Promise.all([a, b]).then()
Promise.myAll = function(args) {
return new Promise((resolve, reject) => {
const results = [];
let count = 0;
let index = 0;
// 这里之所以没有使用forEach等数组循环方法,主要是因为Promise.all可以传入的数据不止是数组
// 参考:https://zhuanlan.zhihu.com/p/362648760
for (let item of args) {
const current = index;
index++;
Promise.resolve(item).then(res => {
results[current] = res;
count++;
// 注意 resolve 的判断条件,没有使用传入参数的长度进行判断,因为它不一定是数组
if (count === index) {
resolve(results);
}
}, error => {
reject(error);
});
}
if (index === 0) {
resolve([]);
}
});
};
const c = new Promise((resolve) => {
setTimeout(() => {
resolve('哈哈哈,我定时了');
}, 3000);
});
const a = Promise.resolve(32);
const b = Promise.resolve(77);
const d = 'dd';
Promise.myAll([c, a, b, d]).then(res => {
console.log(res);
});
console