code q&a
Resources About
Question:

What is async/await?

Async/await lets you write code that waits on asynchronous work like an HTTP request, a database query or a file read without freezing your program. Asynchronous means the result comes back later instead of right away. The waiting code reads top to bottom like normal code, one step after another.

JavaScript used callbacks to handle waiting before async/await existed. You passed in a function that ran once the work finished. Nesting those callbacks several levels deep got painful fast and people called that mess “callback hell.” Promises came next and let you chain steps with .then(). C# made async/await popular in 2012 and JavaScript added it in ES2017 as a nicer way to write promise code. Python and Rust have it too.

Here’s the same API call written both ways:

// With .then()
function showUserWithThen() {
  return fetch("/api/user")
    .then(response => response.json())
    .then(user => console.log(user.name));
}

// With async/await
async function showUserWithAwait() {
  const response = await fetch("/api/user");
  const user = await response.json();
  console.log(user.name);
}

The await keyword pauses only the function it sits in until the promise it’s waiting on settles. The rest of the program keeps running in the meantime, so a server can handle other requests while one request waits on the database. Errors get handled with a regular try/catch block, which feels a lot more natural than tacking .catch() onto a chain.

I remember when async/await was introduced and it made sense right away because I’d dealt with enough nested callbacks to know what a pain they are. The one thing that trips people up is that an async function still returns a promise. A common mistake is forgetting await and getting a Promise object back instead of the value you wanted. You’ll run into that bug a lot when debugging and the fix is usually just adding the missing await.

You might also like