[Javascript] Write Promise.all()

Promise.myAll = function (promises) {
  let res, rej;
  const p = new Promise((resolve, reject) => {
    res = resolve;
    rej = reject;
  });
  let i = 0;
  let result = [];
  // since Promise.all can take any iterable as input
  // to check whether it has items or not, we have to
  // count items one by one, instead of using .length or .size
  for (const promise of promises) {
    const index = i;
    i++;
    Promise.resolve(promise).then((data) => {
      result[index] = data;
      i--;
      if (i === 0) {
        res(result);
      }
    }, rej);
  }
  if (i === 0) {
    return res([]);
  }
  return p;
};

const res = Promise.myAll([1, Promise.resolve(2), Promise.resolve(3), 4]);
res
  .then((data) => {
    console.log(data);
  })
  .catch((err) => {
    console.error(err);
  });

 

posted @ 2024-10-18 14:54  Zhentiw  阅读(2)  评论(0编辑  收藏  举报