3

Is there a difference between these two ways for returning promise from a function

var promise;
promise = callAsync();
promise.then(doSomething).then(doSomethingElse);
return promise;

vs

var promise;
promise = callAsync();
return promise.then(doSomething).then(doSomethingElse);

I thought both approaches are same, but in a mocha test case, only second approach is working.

Jithin
  • 1,108
  • 2
  • 12
  • 26

1 Answers1

4

They are certainly not the same. Each .then() returns a new promise. So,

return promise;

is returning the original promise, but:

return promise.then(doSomething).then(doSomethingElse);

is returning a new promise that is the result of calling both .then() methods. The difference is that the latter one is returning a promise that is influenced by the functions called in those .then() methods, whereas the first promise is only influence by callAsync() and has nothing to do with the other .then() handlers.

The first promise is only monitoring callAsync(). It has absolutely nothing to do with what happens in other .then() handlers. The key to understanding .then() is that it returns a new promise and it is that new promise that is influenced by what happens in the .then() handlers.

For more info, read this answer: Is there a difference between promise.then.then vs promise.then; promise.then to understand the difference between chaining and branching.

Community
  • 1
  • 1
jfriend00
  • 683,504
  • 96
  • 985
  • 979