如何停止使用async-await执行下一个功能?

如何停止使用async-await执行下一个功能?

问题描述:

我正在使用此库在我的nodejs应用程序中链接异步函数: https://github.com/yortus/asyncawait

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

}

因此,bar3等待bar2完成,而bar2等待bar()完成.没关系.但是,为了阻止异步块进一步执行,我该怎么办?我的意思是这样的:

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?

此刻,我在bar内抛出异常并以以下方式处理该异常:

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完全支持 这种语法.只需在函数中return:

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