kuan kuan - 3 years ago 119
Javascript Question

Passing another promise to a promise handler

I expected the promise handler to log the promise

p1
(not the value "A") since
console.log
is called with
p1
directly. However, it somehow logs "A". How is the promise
p1
automatically resolved to "A" without then being called on it ? For example,
console.log(p1)
does not output "A" directly as is expected. Is something going on behind the scenes ?



var p1 = new Promise(function(resolve, reject) {
resolve("A");
});

var p2 = new Promise(function(resolve, reject) {
resolve(p1);
});

p2.then(function(v) {
console.log(v)
});





EDIT: I understand that calling

p1.then((v) => return v))


returns a new promise that is fulfilled with the value v. Unless Im seriously missing something here, the "p1" reference in the second promise constructor should have been passed directly to console.log, resulting in the block

var p2 = new Promise(function(resolve, reject) {
resolve(p1);
});

p2.then(function(v) {
console.log(v)
});


becoming

console.log(p1).


Since console.log is called directly with p1, NOT the result of p1.then(...), p1 should not be resolved into the value "A" in the same way that printing that a another program

var promise = new Promise(function(resolve, reject) {
resolve("B")
})

console.log(promise)


does not result in the string "B".

EDIT2: I had a misconception that the resolve parameter passed to the executor is a wrapper for unfulfilled function, which caused me tons of confusion. Check out Why does the Promise constructor require a function that calls 'resolve' when complete, but 'then' does not - it returns a value instead? for more details.

Answer Source

Resolving a promise to another promise will automatically make it wait for the other promise's result.

This is what makes promises chainable (returning further promises in then() callbacks).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download