javascript 一次捕获多个错误 [英] javascript catch multiple errors with one catch

查看:56
本文介绍了javascript 一次捕获多个错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有 3 个带有 promise 的函数:

Let's say I have 3 functions with promises:

function1().then(() => {
  function2().then(() => {
    function3().then(() => {      
    })
  })
}).catch((err) => {
  console.log(err);
})

我是否能够捕获由 3 个函数中的任何一个返回的错误?如果没有,我应该怎么做才能用一个语句捕获任何函数的 promise 返回的错误?

Would I be able to catch the error returned by any of the 3 functions? If not, what should I do in order to catch the errors returned by any of the functions' promises with one statement?

推荐答案

不是在主体中调用和链接它们,而是返回结果承诺并链接 .then 子句.

Instead of calling and chaining them in the bodies, return the resulting promise and chain the .then clauses.

function1().then(() => {
  // TODO: Something.
  return function2();
}).then(() => { // <-- This `.then` waits until `function2` has finished executing
  // TODO: Something.
  return function3();
}).then(() => { // <-- This `.then` waits until `function3` has finished executing
  // TODO: Something.
}).catch((err) => {
  console.log(err);
});

这篇关于javascript 一次捕获多个错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆