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

How to stop executing next function with async-await?

我正在使用这个库在我的 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)

可以正常使用,但看起来不对

I mean something like this …

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

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

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

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