简体   繁体   English

使用异步等待时无法获得预期的控制台输出

[英]can't get an expect console output when using async await

    function fails4() {
      return new Promise((resolve, reject) => {
        setTimeout(function () {
          reject(new Error());
        }, 100);
      });
    }

    async function myFunc4() {
      try {
        await fails4();
      } catch (e) {
        console.log(e);
        console.log('that failed', e); //<-- this gets called
      }
    }
    async function loadmYScript() {
      try {
        await myFunc4();
      } catch (error) {
        console.log(error);
        console.log(123);
      }
    }
    loadmYScript();

cant't execute the console.log(123) as I expected can anybody help me with this question very appreciated无法按我的预期执行 console.log(123) 任何人都可以帮助我解决这个问题,非常感谢

You're calling loadmYScript, which in turn calls myFunc4, which in turn calls fails4.您正在调用 loadmYScript,而后者又调用 myFunc4,而后者又调用 failed4。 This last one (fails4) throws an error.最后一个(失败4)引发错误。 The error is "catch-ed" by myFunc4.该错误被 myFunc4 “捕获”。 Inside this catch block you don't throw any error, there's only a couple of logs, so the result of loadmYScript is a fulfilled promise with undefined value.在这个 catch 块中你不会抛出任何错误,只有几个日志,所以 loadmYScript 的结果是一个未定义值的已履行承诺。 It is not rejected because myFunc4 doesn't throw the error.它不会被拒绝,因为 myFunc4 不会抛出错误。

If you throw an error inside the catch block of myFunc4, you will have your 123 logged, and the promise will be rejected.如果你在 myFunc4 的 catch 块中抛出一个错误,你将记录你的 123,并且 promise 将被拒绝。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM