简体   繁体   English

为什么异步函数在等待已解决的承诺时返回?

[英]Why async function returns on awaiting for already resolved promise?

Indeed, such behaviour can cause some performance issuses, ie additional context switches between caller "thread" and "continuation tail" of async function.事实上,这种行为会导致一些性能问题,即在异步函数的调用者“线程”和“延续尾部”之间进行额外的上下文切换。

 async function f() { await Promise.resolve("something"); console.log("f: after await"); return "somthing_else"; } function g() { const fres = f(); console.log("g: f returns"); fres.then((x) => console.log("finish")); } g();

The output is (at least in my Chrome):输出是(至少在我的 Chrome 中):

g: f returns
f: after await
finish

Since await operator actually has nothing to wait, I would expect:由于 await 运算符实际上没有什么可等待的,我希望:

f: after await
g: f returns
finish

Is that behaviour specified by standard or it is implementation dependent?该行为是由标准指定的还是依赖于实现的?

If it is standard behaviour what is the reason?如果是标准行为,原因是什么?

f function is async, so you should await for it within g function f函数是异步的,所以你应该在g函数中等待它

async function g(){
  const fres = await f();
  console.log("g: f returns");
  fres.then((x) => console.log("finish"));
}

Promises are placed in a queue that is executed after the current normal script queue is empty. Promise 被放置在一个队列中,该队列在当前普通脚本队列为空后执行。

So you will finish running g() and hence, push console.log("g: f returns");所以你将完成 g() 的运行,因此,push console.log("g: f returns"); to the current stack before f() resolves.在 f() 解析之前到当前堆栈。

If the log was inside the fres.then() function, it would only be logged after f() resolves.如果日志在fres.then()函数内,它只会在f()解析后记录。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM