Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript ES6 promises

Question: What is the difference between these four promises?

doSomething().then(function () { return doSomethingElse(); });

doSomething().then(function () { doSomethingElse(); });

doSomething().then(doSomethingElse());

doSomething().then(doSomethingElse);
like image 473
Tarek Alkhatib Avatar asked Mar 31 '18 20:03

Tarek Alkhatib


1 Answers

Option 1:

doSomething().then(function () { return doSomethingElse(); });

This executes doSomething(), then when it resolves, it executes doSomethingElse() and the resolved value of the promise chain is the resolved value or return value of doSomethingElse(). No arguments are passed to doSomethingElse().

If you were to summarize this option, you'd say it was:

Chained in Sequence, with no parameter passing.


Option 2:

doSomething().then(function () { doSomethingElse(); });

Same as option 1, except the resolved value of the promise chain is undefined because there is no return value from the .then() handler. Any return value from doSomethingElse(), whether a promise or a value is ignored.

If you were to summarize this option, you'd say it was:

Executed in Sequence (not chained), with no parameter passing.


Option 3:

doSomething().then(doSomethingElse());

This is pretty much never what you want. This executes doSomething() and then, before doSomething() has resolved, it also executes doSomethingElse() and passes the return value from doSomethingElse() as the .then() handler. This is a coding mistake unless doSomethingElse() returns a function to be used as the .then() handler.

If you were to summarize this option, you'd say it was:

Executed Immediately, Probably a Bug


Option 4:

doSomething().then(doSomethingElse);

This is the same as option 1 except that the resolved value from doSomething() is passed as the first argument to doSomethingElse(val). This is structurally the same as this:

doSomething().then(function(result) { return doSomethingElse(result)});

If you were to summarize this option, you'd say it was:

Chained in Sequence, with parameter passing.


Other Notes:

  1. If doSomethingElse() returns a promise, then only Options 1 and 4 will add that promise to the chain (because they are the only options that return the promise from the .then() handler) so the chain will wait for that promise to resolve.

  2. In options 1, 2 and 4, if doSomethingElse() throws a synchronous exception, then the promise chain will become rejected with the exception as the reason. In option 3, the function is executed outside the promise chain so if it throws a synchronous exception, it will throw to a higher scope (similar to if doSomething() threw synchronously).

like image 167
jfriend00 Avatar answered Sep 27 '22 21:09

jfriend00