Search code examples
javascriptecmascript-6promisebluebirdes6-promise

javascript and promise: how to refactor/flatten the following nested promises?


I am new to promise, and I am reading a piece of codes which is pretty difficult for me to understand:

  return promise
    .then(function helper0(instances) {
      return helper1(instances, options)
        .then(function helper2() {
            return bluebird.delay(3000)
              .then(function helper3() {
                return helper4(localParams, options);
              });
          }
        });
    });

How to re-factor it to promise.then().then()...? Thanks


Solution

  • Nesting promises is a known anti-pattern, you should chain them instead:

    // the structure is vertical instead of a nested pyramid
    return promise
      .then(function helper0(instances) {
        return helper1(instances, options)
      })
      .then(function helper2() {
        return bluebird.delay(3000);
      })
      .then(function helper3() {
        return helper4(localParams, options);
      });
    

    Returning a promise from the callback passed to then adds that promise to the chain.

    Using arrow functions would clean this up further:

    return promise
      .then(instances => helper1(instances, options))
      .then(() =>  bluebird.delay(3000))
      .then(() =>  helper4(localParams, options);
    

    But note that using named functions would be a better approach for debugging purposes because of a more readable stack trace.