Use “await” only when you want to wait

JavaScript tip for working with async, await, and Promises

John Daley
Jul 23, 2017 · 2 min read

Promises made it easier to write asynchronous code in JavaScript. The new async and await build on top of Promises and make it even easier, especially for beginners. Instead of nesting code with the Promise.then or Promise.catch methods, you can instead use a familiar looking flat try catch structure.

While this works very well it can easily lead to some misconceptions if you haven’t taken the time to learn the basics for working with Promises. You may be tempted to automatically await any asynchronous call. This turns out to be unnecessary and can lead to more verbose and potentially less performant code. In the worse case it may force sequential execution where asynchronous execution is possible.

Consider the following code.

The functions findFoo1 and findFoo2 look suspiciously similar yet findFoo1 is declared as async and uses await while findFoo2 just returns a Promise directly with no fuss. If you were to convert findFoo1 to a promise-only function it would look something like this:

Now it is a little more obvious that using async and await in findFoo1 is unnecessary. Note the return value for the function does not change. In either case where it does or does not declare itself as async it still returns a Promise (async functions wrap the return value in a Promise if it isn’t already a Promise).

However, the extra Promise isn’t the worst part. The default function that calls findFoo1 and findFoo2 awaits the result of each function forcing sequentially execution where parallel execution is possible.

A simple rule to follow is only to use await if you really need to wait on the request and do something with the fulfilled value or handle any errors. Another way of saying it is “once in Promise-land, stay in Promise-land” until you need to leave. Following this rule allows more natural patterns like the following.

Now findFoo1 is no longer using await and the default function now returns a Promise.all so that both queries can run in tandem.

In conclusion, async and await are great additions to JavaScript and can help make asynchronous programs more readable, but they work with Promises and have not replaced them. Avoiding an overuse of await will keep code more concise, performant, and encourage parallel execution patterns.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade