skip to Main Content
var p = new Promise(function(resolve, reject) {
    setTimeout(function() {
        resolve("OK");
    }, 2000);
});

p.then().then(function(data) {
    console.log(data);
});

I don’t understand what happens after the first "then" is called. When the first "then" is called it returns undefined, which in turn resolves Promise created for this "then" with a value "undefined". Yet, for some reason, when the second "then" is called it is passed "OK" as "data" and subsequently logs it. Where did the "data" come from ?

2

Answers


  1. This "forwarding" of the value is intended behaviour. Mozilla contributors write:

    Parameters

    onFulfilled Optional

    A function to asynchronously execute when this promise becomes fulfilled.
    […]

    If it is not a function, it is internally replaced with an identity function ((x) => x) which simply passes the fulfillment value forward.

    Login or Signup to reply.
  2. var p = new Promise(function(resolve, reject) {
        setTimeout(function() {
            resolve("OK");
        }, 2000);
    });
    
    p.then(console.log); // prints ok
    p.then().then().then().then(console.log); // prints ok
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search