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
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 usingthen
/catch
methods.Basically, when you have that
test
const:You have two valid options to write deterministic code:
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.
From MDN:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/Promise#return_value
The returned promise is settled async so we should create a microtask async to aim to the point when the returned promise is settled: