As I plunge into studying Promise
s, my understanding has halted on the following question that I do not find discussed (all I find are specific discussions of the Promise
constructor, and the Promise
'then
' function - but not a discussion that compares their design patterns).
1. The Promise
constructor
From the MDN documentation, we have this use of the Promise constructor (with my comment added):
new Promise(function(resolve, reject) { ... }); // <-- Call this Stage 1
Function object with two arguments resolve
and reject
. The first
argument fulfills the promise, the second argument rejects it. We can
call these functions, once our operation is completed.
2. The then
function
Moving on to the then
function that can be called on a Promise
object (which returns a new Promise
object), we have the following function signature as described by the documentation (with my comments added):
p.then(onFulfilled, onRejected);
Chaining
Because the then
method returns a Promise, you can easily chain then
calls.
var p2 = new Promise(function(resolve, reject) {
resolve(1); // <-- Stage 1 again
});
p2.then(function(value) {
console.log(value); // 1
return value + 1; // <-- Call this Stage 2
}).then(function(value) {
console.log(value); // 2
});
My question
From the above code snippet, it seems clear to me that the value passed to the resolve
function in Stage 1 (in the second occurrence of resolve
- beneath (2), above) is passed on to the next stage (the first then
function that follows in the same code snippet). There is no return value at Stage 1. However, it is the return value at Stage 2 that is passed on to the next stage after that (the second then
function).
Is this lack of correspondence between the design pattern for the creation of a Promise
, and the use of the then
function on an existing promise (which also returns a Promise
), just a historical fluke (one requires calling a callback but returns nothing, and the other returns a value but does not call a callback)?
Or am I missing an underlying reason why the Promise
constructor utilizes a different design pattern than the then
function?
See Question&Answers more detail:
os