I can not understand how the following code run. Why "1" is after "b" but "h" is after "3"?
Shouldn’t the order be a, b, 1, 2, h, 3? Some articles said that the difference between "event loop queue" and "job queue" leads to the following output. But how? I have read the specification of ECMAScript 2015 - 8.4 Jobs and Job Queues, wanting to know how Promise'job works, but it makes me more confused. How can I fix this?
var promise = new Promise(function(resolve, reject) {resolve(1)});
promise.then(function(resolve) {console.log(1)});
console.log('a');
promise.then(function(resolve) {console.log(2);});
setTimeout(function() {console.log('h')}, 0);
promise.then(function(resolve) {console.log(3)});
console.log('b');
// a
// b
// 1
// 2
// 3
// h
I know Promise is asynchronous, but the callback of the setTimeout(..) asynchronous operation is always after Promise's asynchronous operation. Why?