# PromiseAllSettled

Promise.allSettled = function(list) {
  return new Promise((resolve) => {
    const res = [];
    list.forEach((item, index) => {
      item
        .then((r) => {
          res[index] = { status: "fulfilled", value: r };
        })
        .catch((err) => {
          console.log(index);
          res[index] = { status: "rejected", reason: err };
        })
        .finally(() => {
          if (res.filter((v) => v).length === list.length) {
            resolve(res);
          }
        });
    });
  });
};

function a() {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(11);
    }, 200);
  });
}

function b() {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      reject(Error("b 出错了"));
    }, 300);
  });
}

Promise.allSettled([a(), b()]).then((res) => {
  console.log(res);
});

// [
//   { status: 'fulfilled', value: 11 },
//   { status: 'rejected', reason: Error('b 出错了') }
// ]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
Last Updated: 6/27/2023, 7:40:45 PM