0

My codes:

let promise = new Promise(function(resolve, reject){
  console.log('p');
  resolve();
});

promise.then(()=>console.log('r'));


console.log('hi');
console.log('hi');

output:

p
hi
hi
r

I thought that fulfillment handler added to the queue before console.log('hi');. It seems that I am wrong. Any hints? Thanks

BAE
  • 8,550
  • 22
  • 88
  • 171
  • `console.log` isn't added to the queue. It's fired right away. `.then` promise handlers are added to the queue (`setTimeout(handleSuccess, 0);`) so they are very much going to fire after something that happens synchronously. – Norguard Jul 09 '17 at 02:42
  • 1
    `.then()` handlers are always called asychronously per the promise specification. This is done to prevent situations where they are sometimes called synchronously and sometimes call asynchronously which can allow bad bugs to more easily remain undetected. So, since they sometimes must be called asynchronously, the designers decided it was best if they are always called asynchronously. Thus the rest of your synchronous code will always execute before a `.then()` handler is called. – jfriend00 Jul 09 '17 at 04:32

0 Answers0