【问题标题】:Resolves propagating up multiple calling async functions解决了传播多个调用异步函数的问题
【发布时间】:2015-07-27 03:08:55
【问题描述】:

我一直在尝试让我的异步函数的rejects 冒泡回到他们的调用者,但由于某种原因它不起作用。下面是一些经过测试的示例代码:

"use strict";

class Test {
   constructor() {
      this.do1();
   }

   async do1() {
      try { this.do2(); } catch(reason) { console.error(reason); }
   }

   async do2() {
      for(let i = 0; i < 10; i++) {
         await this.do3();
         console.log(`completed ${i}`);
      }
      console.log("finished do1");
   }

   async do3() {
      return new Promise((resolve, reject) => {
         setTimeout(() => {
            if(Math.random() < 0.3) reject('###rejected');
            else resolve("###success");
         }, 1000);
      });
   }
}

export default Test;

Chrome 每次都会给我这个:Unhandled promise rejection ###rejected

知道为什么会这样吗?我希望能够从比do2() 更高的级别处理所有抛出的错误(如果try/catch 在do2() 中并包装await this.do3();,则上面的示例可以正常工作)。谢谢!

编辑:更明确地说,如果我将 try/catch 从 do1() 中取出并将其放入 do2(),如下所示,一切正常:

async do2() {
   try {
      for(let i = 0; i < 10; i++) {
         await this.do3();
         console.log(`completed ${i}`);
      }
      console.log("finished do1");
   } catch(reason) { console.error(reason); }
}

【问题讨论】:

  • await放在this.do2();之前怎么样?
  • 傻我!非常感谢。我接受了你的回答。

标签: javascript async-await promise ecmascript-2016


【解决方案1】:
async do1() {
    try {
        await this.do2();
    }
    catch(reason) {
        console.error(reason);
    }
}

do2 是一个异步函数。并且您在没有await 的情况下调用它。所以,当它完成时,它周围没有 try-catch 子句。

请参阅this questionthis article 了解更多详情。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-11-10
    • 2020-11-07
    • 2010-12-22
    • 2021-03-27
    • 2019-03-27
    • 2019-02-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多