Search code examples
javascriptpromise

why when I resolve a promise, the output is in pending state?


so consider the code below, when I resolve a promise the result is in pending state in the very first moment( I know after I expand the dropdown I will see the expected result but in here I'm questioning the very first moment), while I reject a promise, it shows the expected result in very first moment. so I wonder why is this happening?

code:

 const test = new Promise((resolve, reject) => {
 resolve(Promise.resolve(78))
 })

 console.log(test);

 //output in console:Promise {<pending>}
 const test2 = new Promise((resolve, reject) => {
 reject(Promise.resolve(78))
 })
 
 console.log(test2);

 //output:promise {<rejected>: Promise}

Solution

  • From MDN:

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/Promise#return_value

    Note that if you call resolveFunc or rejectFunc and pass another Promise object as an argument, it can be said to be "resolved", but still not "settled". See the Promise description for more explanation.

    The returned promise is settled async so we should create a microtask async to aim to the point when the returned promise is settled:

    const test = new Promise((resolve, reject) => {
      resolve(Promise.resolve(78))
    })
    
    queueMicrotask(() => queueMicrotask(() => console.log(test)));

    enter image description here