A key difference between .then() and async-await in JavaScript
KyleJB
Posted on September 10, 2020
Asynchronous code can be frustrating when its behaviors are not fully understood. In JavaScript, .then()
and await
are the most commonly used functions for handling asynchronous nature of a Promise
. I'd like to take a stab at demystifying some of the quirks that make JavaScript feel "weird" in order to help us take full advantage of asynchrony.
When learning all about fetch()
and the Promise
fetch()
returns, I was introduced to JavaScript's .then()
function as a means of handling the asynchronous nature of a Promise
. So, what's the deal with async
and await
? Is it just syntactic sugar to avoid .then()
's callback hell? Searching "async vs .then" in google produces front page results such as this stackoverflow post. But, as we all come to know on our coding journey, the devil is in the details...
In order to examine the behaviors of async-await
and then
, I built a small program. First, we need to create a database (I used json-server
) to make our fetch requests.
Then, we need to write two functions that are practically identical save for one detail - one has to use then
and the other has to use async-await
. Take note of the carefully placed console.log
s , as we will be tracking their appearances shortly.
Towards the bottom of the file, I added two additional console.log
s wrapped around my invocation of the aforementioned function, I run both separately like so:
Before you read further, what order will the console.log
s come out in? Do take into account the console.log
s within the function definition themselves too...
The results!
Notice how then
runs through the entire function and then continues the execution after the function invocation before returning back to the function to perform the series of then
operations after the Promise
was resolved?
Contrasting this with Async/Await, the function halts execution within the function scope continues to execute other tasks that follow its invocation before stepping back into the promise upon its resolution; this behavior will continue until all Promises are resolved.
Pan Wangperawong, quoted below, summarizes the differences succinctly in his blog post, which I encourage you to check out if you'd like more context.
async-await
Useful to use if your code works with Promises and needs to execute sequentially. Due to blocking, you might lose some ability to process code in parallel. I've primarily used async-await when making API requests. —Pan Wangperawong
then
If you develop your frontend with React.js, a typical use case might be to display a loading screen until a fetch request returns and then using a setState to update the UI. —Pan Wangperawong
Posted on September 10, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
November 3, 2024
September 15, 2024