手写Promise.all方法

// 手写promiseall
Promise.myall = function(promises) {
  return new Promise((resolve, reject) => {
    if (promises == null || typeof promises[Symbol.iterator] !== 'function') {
      return reject('传入的不是可迭代对象');
    }

    const results = []; // 存储结果
    let completedPromises = 0; // 记录已完成的promise数量
    let index = 0; // 记录当前promise的索引
    let totalPromises = 0; // 记录总promise数量

    for (const p of promises) {
      totalPromises++;
    }

    if (totalPromises === 0) {
      return resolve(results);
    }

    for (p of promises) {
      let i = index;
      Promise.resolve(p).then(res => {
        results[i] = res;
        completedPromises++;
        if (completedPromises === totalPromises) {
          resolve(results);
        }
      }).catch(err => {
        reject(err);
      })
      index++;
    }
  });
};

const promises = [new Promise((resolve, reject) => {
  setTimeout(() => {
    return resolve(1);
  }, 3000)
}), new Promise((resolve, reject) => {
  setTimeout(() => {
    return resolve(2);
  }, 1000)
}), Promise.resolve(3)];

Promise.myall(promises).then((res) => {
  console.log(res);
}).catch((err) => {
  console.log(err);
});
点赞

发表回复

电子邮件地址不会被公开。必填项已用 * 标注