How to stop executing next function with async-await?

大憨熊 提交于 2019-12-12 00:08:49

问题


I'm using this library to chain asynchronous functions in my nodejs app: https://github.com/yortus/asyncawait

var chain = async(function(){

    var foo = await(bar());
    var foo2 = await(bar2());
    var foo3 = await(bar2());

}

So bar3 waits for bar2 to finish and bar2 waits for bar() to finish. That's fine. But what will I do in order to stop the async block from further execution? I mean something like this:

var chain = async(function(){

    var foo = await(bar());
    if(!foo){return false;} // if bar returned false, quit the async block
    var foo2 = await(bar2());
    var foo3 = await(bar2());

}

what's the best approach to handle this?

at the moment I throw an exception within bar and handle the exception in way:

chain().catch(function (err) { //handler, ie log message)

It's working, but it doesn't look right


回答1:


I mean something like this …

asyncawait supports exactly this syntax. Just return from the function:

var chain = async(function(){
    var foo = await(bar());
    if (!foo) return;
    var foo2 = await(bar2());
    var foo3 = await(bar2());
});


来源:https://stackoverflow.com/questions/28835780/how-to-stop-executing-next-function-with-async-await

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!