3

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

它正在工作,但看起来不正确

4

2 回答 2

5

我的意思是这样的……</p>

asyncawait完全支持这种语法。仅从return功能:

var chain = async(function(){
    var foo = await(bar());
    if (!foo) return;
    var foo2 = await(bar2());
    var foo3 = await(bar2());
});
于 2015-03-03T16:34:05.830 回答
0

作为已接受答案的替代方案,根据您的使用情况,您可能希望您bar()的 s 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
});
于 2021-08-09T19:44:39.063 回答