Visualizing Promises

Break on through...

published 2 months agoSep 30th, 2018

updated 2 months agoOct 9th, 2018

credit: junior-ferreira-735237-unsplash.jpg

In order to visualize how Promises execute, let’s define a new method delay(millisecs).

function delay(millisecs) {
  return new Promise(resolve => {
    setTimeout(() => resolve(millisecs), millisecs)

This is a utility method which will resolve once the timeout has passed.

The delay in milliseconds will be passed to .then’s callback.

Let’s look at 4 examples (w/ a corresponding timeline)…

Example #1/4

This shows how console.log()’s execution will be delayed by delay(msec).

delay(1000).then(() => console.log('done'))

Example #2/4

This shows what happens when you execute the function, rather than pass a reference to a function. For example: console.log vs. console.log().

This shows a common mistage using console.log. Generally the desired behavior is shown in Example #1.


Example #3/4

3 Promises execute simultaneously.


Example #4/4

Promise.all with 3 delay Promises. They will execute simultaneously.

Promise.all([delay(1000), delay(2000), delay(3000)])