1

Consider the example:

let promiseA = new Promise((res, rej) => res(10));
let promiseB = new Promise((res, rej) => res(promiseA))

promiseB.then((resolvedVal) => console.log(resolvedVal)); //Outputs 10;

I expect resolvedVal to be promiseA, and not the resolved value of promiseA. Why is this not the case?

I understand this has something to do with the automatic "unwrapping" of promises, but I would like some insight on what exactly is happening under the hood.

  • 1
    https://stackoverflow.com/questions/32168194/fulfill-dont-resolve-promise-with-another-promise – Bergi Jul 28 '18 at 13:11

2 Answers2

0

new Promise((res, rej) => res(promiseA)) is known as promise construction antipattern and there is never a good reason to do that.

This code

let promiseB = new Promise((res, rej) => res(promiseA))

is equivalent to

let promiseB = promiseA;

I expect resolvedVal to be promiseA, and not the resolved value of promiseA. Why is this not the case?

This is how promises work and a reason why this pattern is useful to avoid callback hell. A promise of a value becomes a value when a promise is chained with then.

As Promise/A+ specification states:

The promise resolution procedure is an abstract operation taking as input a promise and a value, which we denote as [[Resolve]](promise, x). If x is a thenable, it attempts to make promise adopt the state of x, under the assumption that x behaves at least somewhat like a promise. Otherwise, it fulfills promise with the value x.

Estus Flask
  • 206,104
  • 70
  • 425
  • 565
0

By definition, you can't return a promise from a promise. It will always chain and resolve/reject. Try this:

let promiseA = new Promise((res, rej) => res(10));
let promiseB = new Promise((res, rej) => res([promiseA]))

promiseB.then((resolvedVal) => console.log(resolvedVal));
//Outputs [promiseA]

;

Steven Spungin
  • 27,002
  • 5
  • 88
  • 78