打字稿处理承诺错误

时间:2021-06-03 15:27:18

标签: node.js typescript async-await promise

在控制器中,我多次调用一些返回承诺的方法。

我将使用 await/async 语句,我有这样的东西:

try {
  let foo = await myFirstMethod();
  let bar = await mySecondMethod();
}catch(e => {
  // which method fails between the both?
});

是的,我知道我可以将调用拆分为两个单独的 try/catch 语句,但我还必须处理这种情况,而且我想了解哪种方法更适合出现特定类型的错误每种方法的响应。

感谢并欢迎任何帮助或建议。

谢谢

1 个答案:

答案 0 :(得分:0)

您要找的是Promise.allSettled

let promises = [myFirstMethod() ,mySecondMethod()];

let allResults = Promise.allSettled(promises).then((results) => {
    // results is an array of objects representing the promises' final state
    // result.status is either "fulfilled" or "rejected"

   results.forEach(result => {
       console.log(result.status);
   });

});