[英]State of Macrotask and Microtask queue during this calculation
This question is very similar in intent to Difference between microtask and macrotask within an event loop context , but more specific, in that it asks for the explication of a definite example: I think for this reason it shouldn't be considered a duplicate. 这个问题非常类似于事件循环上下文中微任务和宏任务之间的区别 ,但更具体,因为它要求明确示例的解释:我认为因此不应该认为它是重复的。
What is the state Macrotask queue and Microtask queue during the execution of this code in node.js 在node.js中执行此代码期间,状态Macrotask队列和Microtask队列是什么
console.log("A1");
(async ()=> {
console.log("1")
f = async ()=>{console.log('2')}
await f()
console.log("3")
})()
console.log("A2");
Output: 输出:
A1
1
2
A2
3
Output I expected: A1, A2, '1','2','3' 我预期的输出:A1,A2,'1','2','3'
Based on this reasoning: log A1 --> enqueue anonymous function on microtask queue --> log A2 --> execute anaonymous function log 1, enqueue f on the microtask queue --> execute f from microtask queue --> log 2 --> log 3 根据这个推理:log A1 - >在微任务队列上排队匿名函数 - > log A2 - >执行匿名函数log 1,在微任务队列上排队f - >从微任务队列执行f - > log 2 - - > log 3
Where am I going wrong? 我哪里错了? (additionally how is a top level async func enqueued?) (另外顶级异步函数如何排队?)
NOTE: actual command used to run this was npx babel-node myscript.js 注意:用于运行它的实际命令是npx babel-node myscript.js
You're seeing this behavior because an async
function runs synchronously up until the first await
, explicit return
, or implicit return
(code execution falling off the end of the function). 您会看到这种行为,因为async
函数同步运行,直到第一次await
,显式return
或隐式return
(代码执行从函数末尾开始)。
I'm going to change the code slightly to give the outer async
function a name so it's easier to talk about: 我将稍微更改代码以使外部async
函数成为名称,因此更容易讨论:
console.log("A1");
const outer = async () => {
console.log("1")
f = async ()=>{console.log('2')}
await f()
console.log("3")
};
outer();
console.log("A2");
Here's what happens: 这是发生的事情:
console.log("A1")
runs (of course). console.log("A1")
运行(当然)。 outer()
is called. 调用outer()
。 outer
runs, so it: outer
运行的同步部分,所以它:
console.log("1")
运行console.log("1")
f
创建f
f()
调用f()
f
runs, so it: f
的同步部分运行,所以它:
console.log('2')
是否console.log('2')
f
implicitly returns, and so it returns its promise to outer
. 此时, f
隐式返回,因此它将其promise返回给outer
。 That promise is already fulfilled with the value undefined
. 价值undefined
已履行了这一承诺。 (See here in the spec.) (见这里的规范。) outer
awaits f
's promise, so it returns its promise to the caller (which throws it away, but that doesn't matter). outer
等待f
的承诺,所以它将其承诺返回给调用者(将其丢弃,但这无关紧要)。 outer
awaiting f
's promise queued a microtask to continue outer
because f
's promise is already settled. outer
等待f
的承诺排队一个微型任务继续outer
因为f
的承诺已经解决。 console.log("A2")
runs. console.log("A2")
运行。 outer
to continue and do console.log("3")
. 微任务运行,允许outer
继续并执行console.log("3")
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.