我有两个功能。一个调用某个东西,另一个从它调用,asyncfunc。我的问题是,如果在 asyncfunc 函数内部抛出错误,我想停止执行函数的其余部分并返回。我发现如果我在 catch 中重新抛出错误,我可以得到这种行为,但之后我需要添加另一个 catch。
那么如果任何 promise 被拒绝,我如何从函数返回? (在这种特定情况下,它们是一个接一个,所以我想我可以使用 .then,但如果它们没有嵌套,我想要相同的结果)。
async function something()
{
await asyncfunc().catch(e => console.error(e));
}
async function asyncfunc()
{
await some_promise.catch(err => { throw new Error(err) }); // Error gets swallowed unless I add another catch
await some_promise2.catch(err => { throw new Error(err) }); // Error gets thrown here, return and don't execute promise 3
var data = await some_promise3.catch(err => { throw new Error(err) });
return data;
}
最佳答案
您可以在 something()
函数中捕获错误,并且您的 asyncFunc
可以在抛出时链接以传播错误:
function something()
{
// You dont need to call async/await, if you are not returning
// and this function only has one call.
asyncfunc().catch(e => console.error(e));
}
// Notice I have removed "async"
function asyncfunc()
{
// its a simple case of chain of Promises.
// to execute it serially you can chain it like this;
return some_promise
.then(some_promise2)
.then(some_promise3)
.catch(error => {
// you can do something like 'log' it
throw error;
})
}
关于node.js - promise 拒绝时从函数返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49899410/