-1

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?

tomerpacific
  • 4,704
  • 13
  • 34
  • 52
  • "*they must be printed in the order in which they are called*" - which calls exactly are you referring to here? – Bergi Aug 06 '23 at 09:47

2 Answers2

-1
x.then((res) => new Promise(function(resolve, reject){
    resolve(res*2);
}))

Is the same as:

x.then((res) => res)
.then(res => res * 2)

You are adding a promise that only creates a new promise, so it's executed first, then * 4 promise then * 2 promise

Konrad
  • 21,590
  • 4
  • 28
  • 64
  • So promises have an ordering of getting resolved? Like all first level promises (I mean in the first then) gets resolved before all second level promises (in second then) and so on? – Shiva Ganesh Aug 06 '23 at 06:14
  • Yes. When you create a promise, it's added to the micro-task queue. If it returns another promise it will be added to the queue, but after it resolves – Konrad Aug 06 '23 at 06:19
-1
let x = new Promise(function(resolve, reject) {
    setTimeout(() => resolve(1), 0);
})
const a = x.then((res) => new Promise(function(resolve, reject){
resolve(res*2);
}))
const b = x.then((res) => res*4)
Promise.race([a, b]).then(res=>console.log(res));

You can see that b Promise is resolved still a promise isn't resolved. That's why the code prints 4 before 2.