The promise-chains works asynchronously no matter if they are resolved immediatelly or not.(无论是否立即解决承诺链,它们都是异步工作的。)
The resolve("World")
was called before the console.log("dummy");
(在console.log("dummy");
之前调用了resolve("World")
console.log("dummy");
) indeed.(确实。) But the then
method is executed asynchronously.(但是then
方法是异步执行的。) So what happens?(那会怎样呢?)
The constructor of new Promise is executed straight away in synchronous context (as you already noticed), therefore hi
is consoled out first.(新Promise的构造函数是在同步上下文中立即执行的(如您已经注意到的),因此首先要控制hi
。) Also the resolving of the promise is done before anything else is logged.(同样,在记录其他任何内容之前,也要完成promise的解析。) Then .(然后 。) then
on the promise is seen and no matter if the promise is already resolved or not at that time, this then
part is added to Event Loop to be executed later.(then
广阔的前景被视为与不管的承诺已经解决或不当时,这then
部分被添加到事件循环以后执行。) Then rest of the code is executed printing dummy
and Hello
.(然后执行其余代码,输出dummy
和Hello
。)
Then asynchronous handling that is driven by Event Loop continues which means it takes resolved event, which is the then
function and execute it.(然后,由事件循环驱动的异步处理将继续,这意味着它将处理已解决的事件, then
由事件函数执行该事件。) This is why World is the last one.(这就是为什么世界是最后一个。) 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…