Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Understanding Async & Await

4 min read

Learning async/await can be daunting. It's something you've been procrastinating on for weeks, if not months!

Anime terminator (learning async/await) haunting girl hiding under a desk (you).

You might know the difference between synchronous and asynchronous code, but you're completely lost in the application of it.

At this rate, it's hard to imagine how you'll everwrap your head around asynchronous JavaScript. 😫

But learning async/await doesn't have to be scary!

With a little guidance and the right approach, you can writemodern asynchronous code that just works. Not next month, or next week, buttoday.

It's true, async/await is unintuitive at first.. but only because you haven't built a mental model for it,yet!

To understand async/await we have to talk a little bit about promises first. Since async/await is built on top of promises, when you're writing async/await you're in fact dealing with promises under the hood.

What's aPromise?

Put simply, aPromise is a JavaScript object that represents a future value. It holds two pieces of information: the promisestate, and avalue orerror (depending on the state).

A promise can be in one of these states:

A promise issettled when the promise has either fulfilled or rejected, but not pending. A promise eventuallyfulfills with a value orrejects with an error (or reason).

new Promise(executor) with state: "pending" on the left. Two arrows pointing to the right. One with resolve("ok") leading to state: "fulfilled" and value: "ok". Another with reject(error) leading to state: "rejected" and reason: error. Both fulfilled and rejected states are considered settled states.

A function that returns a promise is by definition anasynchronous function. (remember this, we'll come back to it later)

Even though the promise is returned synchronously, the valueinside the promise is asynchronous and can only be accessedafter the promise has fulfilled.

What doesawait actually do?

When you add the await keyword in front of a promise you instruct the JavaScript runtime to pause execution inside the current function, wait until the promise settles, and only after the promise has settled, continue executing the rest of the code inside that function.

Awaitguarantees that you have access to an asynchronous value past a certain point. The runtime won't execute any further code inside the function until the promise fulfills with the value (or rejects with an error).

One thing to keep in mind is thatstarting an asynchronous operation and awaiting its result are twoseparate actions. This becomes clear when you write them on different lines.

Therefore, await is solely responsible for pausing further execution until the asynchronous operation has completed. It isnot what starts the asynchronous operation.

How aboutasync?

Theasync keyword grants a special ability to a function.

A function marked as async can pause execution anywhere inside its body. In other words, the function is allowed to use the await keyword. Await canonly be used inside async functions. (you'll understand why in a bit)

An async function has two important properties:

  1. Italways returns a Promise
  2. You can use the await keyword inside its scope

When you return anon-Promise value inside an async function, the value is wrapped inside a Promise before being returned.

asyncfunctiongetFive() {return5;}console.log(getFive());// Promise { ... }

Remember what I said earlier about functions that return a promise — they're by definition asynchronous. Therefore, a function marked as async isalways asynchronous.

A non-async function that returns a promise is also asynchronous. The following code is practically the same as the one above:

functiongetFive() {returnPromise.resolve(5);}console.log(getFive());// Promise { ... }

All other functions are considered synchronous functions.

Decision tree to determine whether a function is synchronous or asynchronous.

Whyasync &await are inseparable

Knowing that await pauses execution inside a function and that a non-async function is synchronous if it doesn't return a promise, you can start to see why the following code doesn't work:

functiongetFive() {// function is not asyncconstfive=awaitfetchFive();// 🚫 doesn't work, can't use awaitreturnfive;}

How cangetFive() synchronously returnfive if it needs to wait forfetchFive() first?

Put differently, how can you wait for an asynchronous value and then proceed to return it synchronously?

You simplycan't.

That's why await can only be used inside a function declared with the async keyword. An async function wraps the return value in a promise which makes the value asynchronous.

Hopefully you have a better understanding of async/await by now. Go ahead and use it in your projects!

Transform Callbacks into Clean Async Code! 🚀

Tired of messy callback code? Download thisFREE 5-step guide to master async/await and simplify your asynchronous code.

In just a few steps, you'll transform complex logic into readable,modern JavaScript that's easy to maintain. With clear visuals, each step breaks down the process so you can follow along effortlessly.

Refactoring Callbacks Guide Preview

You'll also get tips on building scalable Node.js applications about twice a month. I respect your email privacy. Unsubscribe any time.

You might also like

3 Reasons Why Async/Await Is Better Than Chaining Promises

Why use async/await when you can use promises instead? Here's why async/await excels at asynchronous JavaScript code.
Read article

Using Callbacks With Async/Await

How do you make a callback-based asynchronous function work nicely with async/await? You promisify it.
Read article

The Talk That Made Me Finally Understand How the Event Loop Works

What is the event loop and how does it work? After this talk I finally understood asynchronous code in JavaScript/Node.js.
Read article

[8]ページ先頭

©2009-2025 Movatter.jp