await are the most commonly used functions for handling asynchronous nature of a
When learning all about
fetch() and the
.then()function as a means of handling the asynchronous nature of a
Promise. So, what's the deal with
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
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.logs , as we will be tracking their appearances shortly.
Towards the bottom of the file, I added two additional
console.logs wrapped around my invocation of the aforementioned function, I run both separately like so:
Before you read further, what order will the
console.logs come out in? Do take into account the
console.logs within the function definition themselves too...
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.
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
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