JavaScript 中没有 await 的异步函数 [英] Async function without await in JavaScript

查看:19
本文介绍了JavaScript 中没有 await 的异步函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个函数,ab,它们是异步的,前者没有await,后者有await.它们都将一些内容记录到控制台并返回 undefined.调用任一函数后,我会记录另一条消息,并查看该消息是在执行函数体之前还是之后写入的.

I have two functions, a and b, that are asynchronous, the former without await and the latter with await. They both log something to the console and return undefined. After calling either of the function, I log another message and look if the message is written before or after executing the body of the function.

function someMath() {
  for (let i = 0; i < 9000000; i++) { Math.sqrt(i**5) }
}

function timeout(n) {
   return new Promise(cb => setTimeout(cb, n))
}

// ------------------------------------------------- a (no await)
async function a() {
  someMath()
  console.log('in a (no await)')
}

// ---------------------------------------------------- b (await)
async function b() {
  await timeout(100)
  console.log('in b (await)')
}

clear.onclick = console.clear

aButton.onclick = function() {
  console.log('clicked on a button')
  a()
  console.log('after a (no await) call')
}

bButton.onclick = function() {
  console.log('clicked on b button')
  b()
  console.log('after b (await) call')
}

<button id="aButton">test without await (a)</button>
<button id="bButton">test with await (b)</button>
<button id="clear">clear console</button>

如果您在没有 await 的情况下启动测试,该功能似乎是同步的.但是使用await,消息被反转,因为函数是异步执行的.

If you launch test without await, the function seems to work as if it was synchronous. But with await, the messages are inverted as the function is executed asynchronously.

当没有 await 关键字时,JavaScript 如何执行 async 函数?

How does JavaScript execute async functions when no await keyword is present?

实际用例:我有一个 await 关键字,它是有条件地执行的,我需要知道该函数是否同步执行以呈现我的元素:

Real use case: I have an await keyword which is conditionally executed, and I need to know if the function is executed synchronously or not in order to render my element:

async function initializeComponent(stuff) {
   if (stuff === undefined)
      stuff = await getStuff()
   // Initialize

   if (/* Context has been blocked */)
       renderComponent() // Render again if stuff had to be loaded
}

initializeComponent()
renderComponent()

PS:标题有 JavaScript 关键字,以避免与其他语言中的相同问题混淆(即 使用异步而不等待)

推荐答案

Mozilla 文档:

异步函数可以包含一个等待表达式,暂停执行异步函数并等待传递的 Promise 的解析,然后恢复异步函数的执行和返回解析值.

An async function can contain an await expression, that pauses the execution of the async function and waits for the passed Promise's resolution, and then resumes the async function's execution and returns the resolved value.

正如您所假设的,如果不存在 await,则不会暂停执行,然后您的代码将以非阻塞方式执行.

As you assumed, if no await is present, the execution is not paused and your code will then be executed in a non-blocking manner.

这篇关于JavaScript 中没有 await 的异步函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆