skip to Main Content

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}

2

Answers


  1. The Promise is literally a promise: a promise to provide some value later, once some work is done. So to get a value you should either await it, or provide a callback by using then / catch methods.

    Basically, when you have that test const:

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

    You have two valid options to write deterministic code:

    // Use callbacks:
    test
        .then(result => console.log("It's for sure successfully completed."))
        .catch(e => console.log("It's for sure failed at this moment."));
    
    // Use await:
    try {
        const result = await test;
        console.log("It's for sure successfully completed.")
    } catch (e) {
        console.log("It's for sure failed at this moment.")
    }
    

    What you’re observing is just result of some internal implementation, you should not rely on that observation. This actual result could change in other JavaScript engines or in different versions.

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

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