【发布时间】:2025-12-06 08:05:02
【问题描述】:
假设我有三个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
}
【问题讨论】:
-
一般:
try { await stepOne(); await stepTwo(); await stepThree(): } catch ...。但是,您的stepOne不会等待setTimeout解决。如果不更改stepOne的实现,就无法等待setTimeout... -
@deceze:抱歉!等待不是一种选择。更新了我的问题。
-
如果您不能使用
await,那么您将无法通过try..catch捕获错误。您需要将它们与旧的then.then.catch联系起来。 -
@deceze :是的,明白。但是,我想通知需要捕获错误。如果它具有误导性,则不应使用 try.. catch 块。我从问题中删除了它。
-
所以:
stepOne().then(stepTwo).then(stepThree).catch(e => console.error(e))...
标签: javascript node.js asynchronous ecmascript-6