async / await

Write asynchronous code that looks and reads like synchronous code. Discover the modern standard for handling background tasks and the massive performance trap of sequential awaits.

JavaScript7 min readConcept 33 of 62

Synchronous Style, Asynchronous Power

Introduced in ES8 (2017), async and await are syntactic sugar built directly on top of Promises.

They allow you to pause a function until a background task finishes, without needing to write any .then() callback chains.

The try / catch Revival

Because async / await makes asynchronous code look synchronous, it brings back a massive feature that Callback Hell destroyed: the standard try / catch block.

You can now wrap a network request in a normal try block and immediately handle any rejection in the catch block, keeping your error handling centralized and readable.

The Two Rules

1. You can only use the await keyword inside a function that is explicitly marked with the async keyword.

2. An async function *always* returns a Promise, even if you just return 5. JavaScript automatically wraps the return value in a resolved Promise.

Sequential vs Parallel Cost

Run two simulated network requests. Notice how sequential await calls stack their loading times, while parallel execution overlaps them.

The Performance Trap

// The Trap: Sequential Awaits
async function loadData() {
// Waits 1.5s completely
const user = await fetchUser();
// THEN waits another 1.0s
const posts = await fetchPosts();
}
Total Time
0.00s
fetchUser()1.5s
fetchPosts()1.0s
Cost: 1.0s wasted waiting
iIf tasks don't rely on each other, never await them on consecutive lines. Use Promise.all() to execute them in parallel and save massive amounts of loading time!

Check yourself

Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.

  1. 1What does an `async` function always return?
  2. 2Why might writing multiple `await` statements on consecutive lines be bad for performance?
  3. 3How do you handle errors when using `async / await`?

Remember this

  • async / await is syntax sugar on top of Promises.
  • You can only use await inside an async function (or at the top level of a module).
  • An async function always returns a Promise.
  • await pauses the execution of the function until the Promise settles.
  • Error handling is done using standard try / catch blocks.
  • Avoid the sequential trap: don't await independent tasks one after the other.

Done with this concept?

Mark it complete to track your progress. No login needed.