面試總結 - 實現一個promise.all 7.js

promise.all 返回一個promise,then的結果要和promise.all輸入的結果順序一致。若有reject,則按promise.all 輸入的順序,第一個reject被彈出。

/**
 * 實現一個 promise.all()
 */
Promise.all1 = function (promises) {
  let results = new Array();
  return new Promise(async function (resolve, reject) {
    promises.forEach(promise => {
      promise.then(res => {
        results.push(res);
        if (results.length === promises.length) {
          resolve(results);
        }
      });
    });
  });
}

const a = new Promise(function (resolve, reject) {
  resolve('a resolve');
});
const b = new Promise(function (resolve, reject) {
  resolve('b resolve');
});
const c = new Promise(function (resolve, reject) {
  reject('c reject');
});

// Promise.all([a, b])
// .then(res => {
//   console.log(res);
// })
// .catch(err => {
//   console.warn(err);
// });

Promise.all1([a, b, c])
.then(res => {
  console.log(res, '000');
})
.catch(err => {
  console.log(err, 'iiii');
});

何不策高足,先據要路津。 — 《少年派》語錄

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章