0

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

nem035
  • 34,790
  • 6
  • 87
  • 99
BAE
  • 8,550
  • 22
  • 88
  • 171

2 Answers2

3

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.

nem035
  • 34,790
  • 6
  • 87
  • 99
  • Thanks, do you have any suggestions as for https://stackoverflow.com/questions/45292024/mocha-sinon-unit-tests-for-chained-promise? – BAE Jul 25 '17 at 13:49
0

Assuming your functions are also using Bluebird promises, you can chain your promises rather than nesting them like this:

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

If the helperX() functions are not necessarily returning Bluebird promises, then you can do this:

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

When you return a promise from within a .then() handler, that inserts that promise into the chain and the rest of the chain waits for that promise to finish before the chain proceeds. That allows you to to chain like this rather than nesting everything.

jfriend00
  • 683,504
  • 96
  • 985
  • 979
  • Why the downvote? What is wrong with this answer? The first code block offers a simple solution that is not offered in the other answer. – jfriend00 Jul 24 '17 at 21:03
  • Thanks, do you have any suggestions as for https://stackoverflow.com/questions/45292024/mocha-sinon-unit-tests-for-chained-promise? – BAE Jul 25 '17 at 13:50