

Understanding Async & Await
source link: https://dev.to/maximization/understanding-async-await-22o6
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Understanding Async & Await
This article was originally published at https://maximorlov.com/understanding-async-await/
Learning async/await can be daunting. It's something you've been procrastinating on for weeks, if not months!
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 ever wrap 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 write modern asynchronous code that just works. Not next month, or next week, but today.
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 a Promise
?
Put simply, a Promise
is a primitive data type (just like a Number, String, Array, etc.) that represents a future value. It's a JavaScript object with two pieces of information: the promise state, and a value or error (depending on the state).
A promise can be in one of these states:
- pending — initial state, the operation is in progress
- fulfilled — the operation completed successfully
- rejected — the operation failed
A promise is settled when the promise has either fulfilled or rejected, but not pending. A promise eventually fulfills with a value or rejects with an error or reason).
A function that returns a promise is by definition an asynchronous function. (remember this, we'll come back to it later)
Even though the promise is returned synchronously, the value inside the promise is asynchronous and can only be accessed after the promise has fulfilled.
What does await
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.
Await guarantees 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 that starting an asynchronous operation and awaiting its result are two separate 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 is not what starts the asynchronous operation.
How about async
?
The async
keyword grants a special ability to a function.
A function marked as async has the ability to pause execution anywhere inside its body. In other words, the function is allowed to use the await keyword. Await can only be used inside async functions. (you'll understand why in a bit)
An async function has two important properties:
- It always returns a promise
- You can use the await keyword inside its scope
When you return a non-Promise value inside an async function, the value is wrapped inside a Promise before being returned.
async function getFive() {
return 5;
}
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 is always asynchronous.
A non-async
function that returns a promise is also asynchronous. The following code is practically the same as the one above:
function getFive() {
return Promise.resolve(5);
}
console.log(getFive()); // Promise { ... }
All other functions are considered synchronous functions.
Why async
& await
are inseparable
Knowing that await pauses execution inside its body 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:
function getFive() { // function is not async
const five = await fetchFive(); // 🚫 doesn't work, can't use await
return five;
}
How can getFive()
synchronously return five
if it needs to wait for fetchFive()
first?
Put differently, how can you wait for an asynchronous value and then proceed to return it synchronously?
You simply can'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!
Master Asynchronous JavaScript 🚀
Learn how to write modern and easy-to-read asynchronous code with a FREE 5-day email course.
Through visual graphics you will learn how to decompose async code into individual parts and put them back together using a modern async/await approach. Moreover, with 30+ real-world exercises you'll transform knowledge into a practical skill that will make you a better developer.
Recommend
-
126
在很长一段时间里面,FE们不得不依靠回调来处理异步代码。使用回调的结果是,代码变得很纠结,不便于理解与维护,值得庆幸的是Promise带来了.then(),让代码变得井然有序,便于管理。于是我们大量使用,代替了原来的回调方式。但是不存在一种方法可以让当前的执行流...
-
76
ASP.NET 谨用 async/await
-
75
C# 5.0 引入 async/await 关键字,旨在简化异步编程模型,抛去语法糖就是 Net4.0 的 Task + 状态机。其实在处理异步编程使用 Task 还是挺简单的,不过既然推出了新的语法糖,难免会尝试一下,然而在使用中却没想象中那么单纯。以下针对ASP.NET 应用程序实际使用过...
-
82
So I finally hopped on the boat with usa...
-
44
I’m really excited to announce the culmination of much of our work over the last four months: a pair of RFCs for supporting async & await notation in Rust. This will be very impactful for Rust in the network services...
-
70
Node.js express.js MongoDB JWT REST API - Basic Project Skeleton Getting started This is a basic API REST skeleton written on JavaScript using async/await. Great for building an MVP for your front-en...
-
56
看到彭总写的文章 这破 Python ,感慨颇多,我也来灌水吧。 首先,我司算是在国内比较敢于尝试新东西的公司吧,最直接的提现就在于我们会及时跟进社区相关基础服务的迭代...
-
50
什么是async? 现在面对日常工作时,总避免不了面对异步操作带来的一些麻烦。在时代演变的过程中,处理异步的方法有许多种:回调函数、Promise 链式语法、Generator 函数到现在比较流行的 async 函数。那什么是 async 呢? async
-
57
I wanted to post a quick update on the status of the async-await effort. The short version is that we’re in the home stretch for some kind of stabilization, but there remain some significant questions...
-
10
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK