skip to Main Content

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


  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

    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search