About Project Insights

What is the difference between these four promises?

6 May 2023

A Promise is an object representing the eventual completion or failure of an asynchronous operation. Since most people are consumers of already-created promises, this guide will explain consumption of returned promises before explaining how to create them.

Essentially, a promise is a returned object to which you attach callbacks, instead of passing callbacks into a function. Chained in Sequence, with no parameter passing.


Option 1 : Chained in Sequence, with no parameter passing.

1doSomething().then(function () { 
2  return doSomethingElse(); 
3});

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(). Chained in Sequence, with no parameter passing.


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

1doSomething().then(function () { 
2  doSomethingElse(); 
3});

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.


Option 3 : Executed Immediately, Probably a Bug

1doSomething().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.


Option 4 : Chained in Sequence, with parameter passing.

1doSomething().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:

1doSomething().then(function () { 
2  return doSomethingElse(); 
3});

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).

Thanks for diving into my world. The future is built by dreamers and doers — let’s create something legendary.

Linkedin Email