在Javascript中没有等待的异步功能 [英] Async function without await in Javascript

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

问题描述

我有两个函数 a b 是异步的,前者没有等待和后面的等待。它们都会将某些内容记录到控制台并返回 undefined 。在调用任何一个函数后,我记录另一条消息,看看是否在执行函数体之前或之后写入了消息。

I have two functions a and b that are asynchronous, the former without await and the later 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 body of the function.

function someMath() {
  for (let i = 0; i < 3000000; 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() {
  a()
  console.log('after a (no await) call')
}

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

<button id="aButton">test without await</button>
<button id="bButton">test with await</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 message are inverted as the function is executed asynchronously.

所以我的问题是:当没有等待关键字时,javascript如何执行 async 函数?

So my question is: how javascript execute async functions when no await keyword is present?

真实用例:我有等待关键字是条件执行的,我需要知道函数是否同步执行才能呈现我的元素:

Real use case: I have an await keyword which is conditionnaly 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:title有javascript关键字,以避免与其他语言中的相同问题混淆(即< a href =https:// st ackoverflow.com/q/12016567/6320039>无需等待即可使用async )

推荐答案

来自mozilla doc:

from mozilla doc:


异步函数可以包含一个await表达式,它暂停
执行异步函数并等待传递的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.

正如您所假设的,如果没有等待,则执行不会暂停,您的代码将同步执行。

As you assumed, if no await is present the execution is not paused and your code will then be executed synchronously.

https://developer.mozilla.org/en-US/docs/Web/ JavaScript /参考/语句/ async_function#Description

这篇关于在Javascript中没有等待的异步功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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