javascript 中的 async/await 示例

Posted

技术标签:

【中文标题】javascript 中的 async/await 示例【英文标题】:an example of async/await in javascript 【发布时间】: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");对理解有帮助吗? 【参考方案1】:

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

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

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

【讨论】:

"当你在函数前添加 async 时,它会同步执行" - 没有。

以上是关于javascript 中的 async/await 示例的主要内容,如果未能解决你的问题,请参考以下文章

Javascript中的async await

Javascript中的async await

理解 JavaScript 的 async/await

在 Javascript 中的 API 调用之间使用 ASYNC/AWAIT 中的数组方法

我可以使用 async/await 来等待 JavaScript 中的多个事件吗?

async/await 函数中的 JavaScript Promise 解析最终响应数组