2022-09-18笔试题00
请注意,本文编写于 531 天前,最后修改于 531 天前,其中某些信息可能已经过时。

面试高频手撕代码题

Promise 系列

实现 Promise.allSettled()

const promiseAllSettled = promises => {
  if (!Array.isArray(promises)) {
    throw new TypeError('Promises must be an array!');
  }

  return new Promise((resolve, reject) => {
    let len = promises.length;
    let result = [];
    promises.forEach((promise, index) => {
      Promise.resolve(promise).then(
        value => {
          result[index] = {
            status: 'fulfilled',
            value,
          };

          len--;
          if (len === 0) {
            resolve(result);
          }
        },
        reason => {
          result[index] = {
            status: 'rejected',
            reason,
          };

          len--;
          if (len === 0) {
            resolve(result);
          }
        }
      );
    });
  });
};

// test
const p1 = Promise.resolve(3);
const p2 = Promise.reject(12);
const p3 = new Promise((resolve, reject) => {
  setTimeout(resolve, 1000, 'done');
});
const p4 = new Promise((resolve, reject) => {
  setTimeout(reject, 200, 'yes');
});

promiseAllSettled([p1, p2, p3, p4]).then(res => {
  console.log(res);
  // res:
  // [
  //     {
  //         "status": "fulfilled",
  //         "value": 3
  //     },
  //     {
  //         "status": "rejected",
  //         "reason": 12
  //     },
  //     {
  //         "status": "fulfilled",
  //         "value": "done"
  //     },
  //     {
  //         "status": "rejected",
  //         "reason": "yes"
  //     }
  // ]
});

本文作者:前端小毛

本文链接:

版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!