Javascript Javascript中没有等待的异步函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/45594596/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 03:07:30  来源:igfitidea点击:

Async function without await in Javascript

javascriptasynchronousasync-await

提问by Ulysse BN

I have two functions aand bthat are asynchronous, the former without awaitand 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 the body of the function.

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

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>

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

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

So my question is: how javascript execute asyncfunctions when no awaitkeyword is present?

所以我的问题是:当不存在关键字时,javascript 如何执行async函数await



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

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

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()

P.S: title has the javascript keyword to avoid confusion with same questions in other languages (i.e Using async without await)

PS:标题有 javascript 关键字,以避免与其他语言中的相同问题混淆(即使用 async 而没有 await

采纳答案by Karim

from mozilla doc:

来自mozilla 文档

An async function cancontain 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 表达式,它暂停异步函数的执行并等待传递的 Promise 的解析,然后恢复异步函数的执行并返回解析的值。

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.

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

回答by NAVIN

Everything is synchronous until a Javascript asynchronous function is executed. In using async-await awaitis asynchronous and everything after await is placed in event queue. Similar to .then().

在执行 Javascript 异步函数之前,一切都是同步的。使用 async-awaitawait是异步的,await 之后的所有内容都放在事件队列中。类似于.then()

To better explain take this example:

为了更好地解释,举个例子:

function main() {
  return new Promise( resolve => {
    console.log(3);
    resolve(4);
    console.log(5);
  });
}

async function f(){
    console.log(2);
    let r = await main();
    console.log(r);
}

console.log(1);
f();
console.log(6);

As awaitis asynchronous and rest all is synchronous including promise thus output is

由于await是异步的,其余的都是同步的,包括承诺,因此输出是

1
2
3
5
6
// Async happened, await for main()
4

Similar behavior of main()is without promise too:

的类似行为main()也没有承诺:

function main() {
    console.log(3);
    return 4;
}

async function f(){
    console.log(2);
    let r = await main();
    console.log(r);
}

console.log(1);
f();
console.log(5);

Output:

输出:

1
2
3
5
// Asynchronous happened, await for main()
4

Just removing awaitwill make whole asyncfunction synchronous which it is.

只是删除await将使整个async功能同步。

function main() {
    console.log(3);
    return 4;
}

async function f(){
    console.log(2);
    let r = main();
    console.log(r);
}

console.log(1);
f();
console.log(5);

Output:

输出:

1
2
3
4
5

回答by Barmar

The function is executed the same with or without await. What awaitdoes is automatically wait for the promise that's returned by the function to be resolved.

无论是否使用 ,该函数的执行方式都相同await。什么await是自动等待由函数返回的承诺被解决。

await timeout(1000);
more code here;

is roughly equivalent to:

大致相当于:

timeout(1000).then(function() {
    more code here;
});

The async functiondeclaration simply makes the function automatically return a promise that's resolved when the function returns.

async function声明只是使功能自动返回的问题得以解决函数返回时的承诺。

回答by tevemadar

As other answers say/indicate: an async functionjust runs on spot until it encounters an await- if there is no await, it runs completely.

正如其他答案所说/表明的那样: anasync function只是在现场运行,直到遇到一个await- 如果没有await,则它会完全运行。

What may be worth adding that asyncunconditionally makes your result a Promise. So if you return something, there is a difference already and you simply can not get the result without returning to the JS engine first (similarly to event handling):

可能值得添加的是async无条件地使您的结果成为Promise. 所以如果你返回一些东西,已经有区别了,如果不首先返回到 JS 引擎,你根本无法得到结果(类似于事件处理):

async function four(){
  console.log("  I am four");
  return 4;
}
console.log(1);
let result=four();
console.log(2,"It is not four:",result,"Is it a promise ?", result instanceof Promise);
result.then(function(x){console.log(x,"(from then)");});
console.log(3);