简体   繁体   中英

How to stop executing next function with async-await?

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

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());
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM