Save this link in your quiver. Learn its reduce algorithm, and never again use nested timeouts.

This:

setTimeout(() => {
  console.log('hello');

  setTimeout(() => {
    console.log('world');
  }, 1000);
}, 1000);

Becomes this:

const messages = ['hello', 'world'];

const promises = messages.map(message => () => new Promise(resolve => {
  setTimeout(() => {
    console.log(message);
    resolve();
  }, 1000);
}));

promises.reduce((promise, func) => promise.then(func), Promise.resolve());

This example looks silly (“you’ve introduced needless complexity!”) but when you have a large set of promises that need to be linearly resolved, you’ll be glad you had this.