首页 > 解决方案 > 如果序列中的一个 Promise 抛出错误,则按顺序解析 Promise 并中断该序列

问题描述

假设我async设置了三个功能,如下所示:

const stepOne = async () => { setTimeout(function() {
  console.log("step 1")
}, 3000)  }

const stepTwo = async () => { throw new Error("Error at step two") }

const stepThree = async () => { console.log("step 3") }

我将如何按顺序执行所有这些函数并在 stepTwo 中断承诺链,不允许 stepThree 函数运行?

所以,

正常顺序是这样的:stepOne --> stepTwo --> stepThree

在 stepTwo 引发错误的序列:stepOne --> stepTwo

stepTwo 抛出的错误需要在 end catch 块中捕获。

更新#1:错过了问题的关键要素。await 不能使用,因为这三个函数需要在非异步函数中调用。

例子:

const testFunc = () => { 
  
  resolve three promises 
  sequentially, break the promise chain when error is thrown 
  and ultimately, catch errors here
   
  }

标签: javascriptnode.jsasynchronousecmascript-6

解决方案


如果您要解决承诺,您的代码将起作用,stepOne因为setTimeout只是将函数添加到堆栈中并且不等待它解决。

如果您将返回一个 PromisestepOne并在之后解决它,console.log那么try catch将等待stepOne并捕获错误stepTwo

这是您的代码示例

const stepOne = async () => {
    return new Promise((resolve, reject) => {
        setTimeout(function() {
            console.log("step 1")
            resolve(true);
        }, 3000)
    });
}

const stepTwo = async () => { throw new Error("Error at step two") }

const stepThree = async () => {
    return new Promise((resolve, reject) => {
        setTimeout(function() {
            console.log("step 3")
            resolve(true);
        }, 3000)
    });
}


(() => {
    stepOne()
        .then(stepTwo)
        .then(stepThree)
        .catch(error => {
            console.log(error);
        })  
})();

现在console.log看起来像这样

step 1
Error: Error at step two
    at stepTwo (/home/user/develop/test/stackoverflow.js:10:38)
    at processTicksAndRejections (internal/process/task_queues.js:93:5)

推荐阅读