Search code examples
javascriptpromiseflow-controles6-promise

What does `x = x.then()` do in promises?


I am trying to understand some code that has a novel approach to promises:

var sequence = Promise.resolve();

sequence = sequence.then(
    function() {
        // success function
    }
);

sequence = sequence.then(
    function(keyPair) {
        // success function
    },
    function(err) {
        // err function
    }
);

sequence = sequence.then(
    function(keyPair) {
        // success function
    },
    function(err) {
        // err function
    }
);

How does this differ from the normal chained .then approach? Is it safe to use?


Solution

  • How does this differ from the normal chained .then approach?

    Not at all. You can eliminate that sequence variable and chain the .then() method calls directly, and you'd get exactly the same behaviour from your promises.

    Is it safe to use?

    Yes.

    Why would I use it?

    Usually, you shouldn't. It's (apparently) just confusing, there is no need for that sequence variable, and it's just longer. Creating variables with descriptive names can make code more verbose and easier to understand, but sequence is just meaningless.

    However, there is one advantage: You can build dynamic chains. You can put some of those assignments in if blocks, or even use loops, to build promise chains of variable length and behaviour. By evaluating the conditions synchronously before the promise callbacks are executed, this might even be advantageous for performance (though creating a larger number of promise objects in memory) when compared to putting all the control flow inside the promise callbacks. Regardless, different and descriptive variables should be used for such an approach, instead of repeatedly reassigning to the same variable.