-1

Recently, I read a post about the best practice for using Promise. The article calls it a "side effect" when we call a function inside the .then() without actually returning a result.

somePromise().then(function () {
  someOtherPromise();
}).then(function () {
  // Gee, I hope someOtherPromise() has resolved!
  // Spoiler alert: it hasn't.
});

Generally, I understand why it's a good practice using the return keyword other than just calling the function. But I'm still curious why we use the phrase "side effect" here.

hackjutsu
  • 8,336
  • 13
  • 47
  • 87

1 Answers1

1

It can be a side effect since you are not actually aware of the results that the execution of the promise can generate. But it is not always a side effect.

If the function call (in this case someOtherPromise) always executes the way you expect it to execute, then it is not a side effect. But since the promise can fail, and you may not be aware if it does (since you are not treating the result), then you may have one.

By side effect, one can understand an effect that is secondary to the one that was expected. If the promise you are calling without caring to the result, behaves differently from what you expected, then it is a side effect.

So, to mitigate a possible side effect you can either:

  1. Return the promise or
  2. Treat it in a then/catch block (can lead to waterfall code, but sometimes is the best choice).

As shown below:

//1.
somePromise().then(function () {
    return someOtherPromise();
}).then(function () {});
//2.
somePromise().then(function () {
    someOtherPromise().then(...).catch(...);
}).then(function () {});
hackjutsu
  • 8,336
  • 13
  • 47
  • 87
igor.araujo
  • 1,007
  • 1
  • 7
  • 15