denysdovhan / wtfjs

🤪 A list of funny and tricky JavaScript examples
http://bit.ly/wtfjavascript
Do What The F*ck You Want To Public License
34.95k stars 2.55k forks source link

Add "resolve() won't return Promise instance" #119

Closed libook closed 3 years ago

libook commented 5 years ago

resolve() won't return Promise instance

const theObject = {
  "a": 7,
};
const thePromise = new Promise((resolve, reject) => {
  resolve(theObject);
}); // -> Promise instance object

thePromise.then(value => {
  console.log(value === theObject); // -> true
  console.log(value); // -> { a: 7 }
})

The value which is resolved from thePromise is exactly theObject.

How about input another Promise into the resolve function?

const theObject = new Promise((resolve, reject) => {
  resolve(7);
}); // -> Promise instance object
const thePromise = new Promise((resolve, reject) => {
  resolve(theObject);
}); // -> Promise instance object

thePromise.then(value => {
  console.log(value === theObject); // -> false
  console.log(value); // -> 7
})

💡 Explanation:

If the value (which is inputted into resolve function) is a thenable (i.e. has a "then" method), the returned promise will "follow" that thenable, adopting its eventual state; otherwise the returned promise will be fulfilled with the value.

Promise.resolve() on MDN

The specification is ECMAScript 25.6.1.3.2 Promise Resolve Functions. But it is not quite human-friendly.

libook commented 3 years ago

@denysdovhan Finally. Conflicts are resolved. Please review.

libook commented 3 years ago

Also updated information from MDN.

denysdovhan commented 3 years ago

Thank you!