JS 简易模拟Promise.all
模拟实现:
Promise._all = function(promises) { // 用来存储入参列表中所有promise的返回结果 const result = []; // promise列表的长度 const size = promises.length; // 已经处于 fulfilled 状态的promise数量 let cnt = 0; return new Promise((resolve, reject) => { // 遍历promises promises.forEach((prom, i) => { Promise.resolve(prom) // 顺利得到返回结果后 .then(res => { result.push(res); cnt++; // 所有promise处于fulfilled状态则返回结果 if (cnt === size) resolve(result); }) .catch(reject); }); }); };