For more tips like this, sign up to the weekly newsletter!

Start a Promise chain with Promise.resolve()

When you start a Promise chain, you need a Promise. The easiest way is to use the first step as the base and then() the subsequent ones.

This practice gives a structure like this:

doSomethingAsync()
  .then(doSomethingElse)
  .then(doSomethingElse2)

If the first step isn't special in any way, this structure is misleading. In that case, a flat indentation is preferred. For that, start the chain with Promise.resolve():

Promise.resolve()
  .then(doSomethingAsync)
  .then(doSomethingElse)
  .then(doSomethingElse2)

This way every async operation is at the same indentation level.

Processing results

There is a different kind of async processing: when you get a value in the first call and process it in subsequent ones.

In that case, it's better to use two indentation levels, as the first step is clearly different from the rest:

getSomething()
  .then(processSomething)
  .then(processSomethingFurther)
Try it
Learn more: