Node.js 承诺拒绝时从函数返回
我有两个功能。一个调用某物,另一个从中调用asyncfunc。我的问题是,如果在asyncfunc函数中抛出错误,我希望停止执行函数的其余部分并返回。我发现,如果我在捕获中重新抛出错误,我可以得到这种行为,但之后我需要添加另一个捕获 那么,如果任何承诺被拒绝,我如何从函数返回?(在这个特定的例子中,它们是一个接一个的,所以我想我可以使用。然后,但是如果它们不是嵌套的,我希望得到相同的结果)Node.js 承诺拒绝时从函数返回,node.js,promise,Node.js,Promise,我有两个功能。一个调用某物,另一个从中调用asyncfunc。我的问题是,如果在asyncfunc函数中抛出错误,我希望停止执行函数的其余部分并返回。我发现,如果我在捕获中重新抛出错误,我可以得到这种行为,但之后我需要添加另一个捕获 那么,如果任何承诺被拒绝,我如何从函数返回?(在这个特定的例子中,它们是一个接一个的,所以我想我可以使用。然后,但是如果它们不是嵌套的,我希望得到相同的结果) 您可以在something()函数中捕获错误,您的asyncFunc可以链接起来,以便在抛出时传播错误:
您可以在
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;
})
}
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;
})
}