I have the following code
let x = new Promise(function(resolve, reject) {
setTimeout(() => resolve(1), 0);
})
x.then((res) => new Promise(function(resolve, reject){
resolve(res*2);
}))
.then((res) => console.log(res))
x.then((res) => res*4)
.then((res) => console.log(res))
console.log("Out")
My doubt is, why does the code print 4 before 2. I know that a then() returns a promise. So in this case they must be printed in the order in which they are called. But why does this not happen?
2
Answers
Is the same as:
You are adding a promise that only creates a new promise, so it’s executed first, then
* 4
promise then* 2
promiseYou can see that b Promise is resolved still a promise isn’t resolved.
That’s why the code prints 4 before 2.