如何使用async-await停止执行下一个函数?

时间:2015-03-03 15:37:01

标签: javascript node.js async-await ecmascript-7

我正在使用这个库在我的nodejs应用程序中链接异步函数: 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()完成。没关系。但是,为了阻止异步块进一步执行,我该怎么做?我的意思是这样的:

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

}

处理此问题的最佳方法是什么?

此刻我在bar中抛出异常并处理异常:

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

它有效,但看起来不正确

2 个答案:

答案 0 :(得分:3)

  

我的意思是这样......

asyncawait支持完全这种语法。只需return来自函数:

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

答案 1 :(得分:0)

作为已接受答案的替代方案,根据您的使用情况,您可能希望您的 bar()throw/reject。

async function bar() {
  try {
    Api.fetch(...) // `fetch` is a Promise
  } catch (err) {
    // custom error handling
    throw new Error() // so that the caller will break out of its `try`

    // or re-throw the error that you caught, for the caller to use
    throw err
  }

  // or, instead of a try/catch here, you can just return the Promise
  return Api.fetch(...)
}

var chain = async(function(){
  try {
    // if any of these throw or reject, we'll exit the `try` block
    var foo = await(bar());
    var foo2 = await(bar2());
    var foo3 = await(bar2());
  } catch {} // ES2019 optional catch. may need to configure eslint to be happy
});