简体   繁体   中英

How do Promises handle immediate resolution?

Experimenting with Promises, found something I didn't expect.

 function Delayer(time){ return new Promise((resolve,reject)=>{ if(time != 0){ setTimeout(()=>resolve("Waited " + (time/1000) + " secs!"),time) } else{ resolve("No Time Waited"); } }) } var output = "Promise not resolved yet!"; console.log(output); Delayer(10).then(function(msg){output = msg; console.log(output)}); console.log(output);//this wont change until callback. Delayer(0).then(function(msg){output = msg; console.log(output)}); console.log(output); 

I expected this Promise to resolve like this:

> Promise not resolved yet!
> Promise not resolved yet!
> No Time Waited
> No Time Waited
> Waited 3 secs!

Instead I get 3 "not resolved yet"s and only one "no time waited". It's clearly waiting until the rest of the code finishes before handling the immediate resolve. How does it do this?

What is the design best practice when creating a promise that might resolve immediately?

The specification for promises requires that they always invoke the callback asynchronously, even if the promise is already in a resolved state. This is a very beneficial quality, because you can be sure that your code will always execute in the same order, whether or not it has to wait. If promises sometimes invoked the callback synchronously, then the order of execution would depend on the internal state of the promise, possibly leading to bugs.

In particular, see requirement 2.2.4 of the Promise a+ spec :

onFulfilled or onRejected must not be called until the execution context stack contains only platform code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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