Promise callbacks returning promises

后端 未结 4 802
谎友^
谎友^ 2020-12-12 16:30

With regard to these great two sources: NZakas - Returning Promises in Promise Chains and MDN Promises, I would like to ask the following:

Each time that we return a

4条回答
  •  长情又很酷
    2020-12-12 17:04

    Basically p3 is return-ing an another promise : p2. Which means the result of p2 will be passed as a parameter to the next then callback, in this case it resolves to 43.

    Whenever you are using the keyword return you are passing the result as a parameter to next then's callback.

    let p3 = p1.then(function(value) {
        // first fulfillment handler
        console.log(value);     // 42
        return p2;
    });
    

    Your code :

    p3.then(function(value) {
        // second fulfillment handler
        console.log(value);     // 43
    });
    

    Is equal to:

    p1.then(function(resultOfP1) {
        // resultOfP1 === 42
        return p2; // // Returning a promise ( that might resolve to 43 or fail )
    })
    .then(function(resultOfP2) {
        console.log(resultOfP2) // '43'
    });
    

    Btw, I've noticed that you are using ES6 syntax, you can have a lighter syntax by using fat arrow syntax :

    p1.then(resultOfP1 => p2) // the `return` is implied since it's a one-liner
    .then(resultOfP2 => console.log(resultOfP2)); 
    

提交回复
热议问题