【问题标题】:an example of async/await in javascriptjavascript 中的 async/await 示例
【发布时间】:2022-01-24 04:35:23
【问题描述】:

我正在学习javascript中的async和await,我在玩async和await时对我写的以下函数的执行顺序有点困惑:

const promiseA = new Promise((resolutionFunc, rejectionFunc) => {
  setTimeout(() => resolutionFunc(666), 5000);
});

const test = async () => {
  await promiseA.then((val) =>
    console.log("asynchronous logging has val:", val)
  );
};

const testTwo = () => {
  test();
  console.log("immediate logging");
};

testTwo();

我的理解是在函数中,先执行,它被调用&执行,是一个异步函数,我把await放在了promise的前面.

为什么console.log("immediate logging");这行代码首先被执行?

另一方面,如果我写 如下:

const testTwo = async () => {
  await test();
  console.log("immediate logging");
};

一切正常

【问题讨论】:

  • 当您同步调用测试时,异步操作会被放入所谓的事件循环。随后的所有同步操作都将在事件循环中异步操作的未决决议之前运行。所以你会看到同步日志......然后事件循环运行承诺解决方案。如果你使用await,则代码在解析后运行
  • 看来你已经知道为什么在test()的异步日志之前执行了:因为你没有await呢?
  • test函数的第一行加上console.log("Starting test");对理解有帮助吗?

标签: javascript async-await promise


【解决方案1】:

当你在函数之前添加 async 时,它会同步执行。这就是为什么当您在 testTwo 中的匿名函数之前保持异步时,它正在等待 test 执行然后它将呈现“立即日志记录”。

请参阅这些链接以了解有关 async/await 的更多信息

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function

【讨论】:

  • "当你在函数前添加 async 时,它会同步执行" - 没有。
猜你喜欢
  • 2018-10-24
  • 1970-01-01
  • 2017-02-18
  • 1970-01-01
  • 2018-01-21
  • 2017-04-29
  • 2020-03-25
  • 1970-01-01
  • 2018-06-27
相关资源
最近更新 更多