Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
347 views
in Technique[技术] by (71.8m points)

javascript - 使用promise时的执行顺序(executation sequence when use promise)

Below is the example code:(下面是示例代码:)

var promise1 = new Promise(function(resolve, reject) { console.log("Hi") resolve("World") }).then(function(value) { console.log(value); }); console.log("dummy"); console.log("Hello"); the output is(输出是) Hi(你好) dummy(假) Hello(你好) World(世界) I'm a little bit confused, because resolve("World") was executed before console.log("dummy");(我有点困惑,因为resolve("World")是在console.log("dummy");之前执行的console.log("dummy");) and console.log("Hello");(和console.log("Hello");) , since the promise is resolved, then the function in then clause should be called immediately.(,由于承诺已解决,因此then子句中的函数应立即调用。) so it should be more sense if the output is:(因此,如果输出为:) Hi(你好) World(世界) dummy(假) Hello(你好) or the function might execute between last two statements, therefore the output is:(否则函数可能在最后两个语句之间执行,因此输出为:) Hi(你好) dummy(假) World(世界) Hello(你好) so why no matter how many time I tried, the output is always the first case?(那么为什么不管我尝试多少次,输出总是第一种情况?)   ask by amjad translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 .(然后执行其余代码,输出dummyHello 。) 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.(这就是为什么世界是最后一个。)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...