zl程序教程

您现在的位置是:首页 >  前端

当前栏目

[Javascript Tips] Use Promise.allSettled instead of Promise.all

JavaScript of use all Promise Tips instead
2023-09-14 08:59:11 时间

Promise.all: 

Problem: let's say we have two promises, P1, P2, P1 reject in 1s, and P2 reject in 3s.

What will happen in catch block?

It only able to catch P1's error, P2's error will be unhandled error

function P1() {
  return new Promise((res, rej) => {
    setTimeout(() => {
      rej(new Error("p1"));
    }, 1010);
  });
}

function P2() {
  return new Promise((res, rej) => {
    setTimeout(() => {
      rej(new Error("p2"));
    }, 3000);
  });
}

async function main() {
  try {
    const [r1, r2] = await Promise.all([P1(), P2()]);
  } catch (err) {
    console.error("main catch", err); // [ERR]: "main catch",  p1
  }
}

main();

 

How to solve the problem?

By using Promise.allSettled:

function P1(): Promise<number> {
  return new Promise((res, rej) => {
    setTimeout(() => {
      rej(new Error("err: p1"));
    }, 1010);
  });
}

function P2(): Promise<number> {
  return new Promise((res, rej) => {
    setTimeout(() => {
      rej(new Error("err: p2"));
    }, 3000);
  });
}

function handle(results: Array<PromiseSettledResult<number>>) {
  results.forEach((res) => {
    if (res.status === "fulfilled") {
      console.log(res.value);
    } else {
      console.log(res.reason);
    }
  });
}

async function main() {
  const results = await Promise.allSettled([P1(), P2()]);
  handle(results);
  /**
  * [LOG]: err: p1 
    [LOG]: err: p2 
  */
}

main();