What is Async/await in JS and why should you use it?

What is Async/await in JS and why should you use it?

In this blog post, we are going to discover:

  • What is Async/await?
  • Why is it required?
  • Key points

Prerequisites:

  • Basic knowledge of promises.

Before diving into async/await, let's see why is it required?

fetchAPi
    .then((data) => {
        // perform operations with the data
    }
    .catch((error) => {
        // handle error
   };

The above seems simple and has no issues. Now, let us consider a complex scenario of nested promises.


readFile
    .then((fileData) => {
        fetchApi(fileData)
            .then((response) => {
                fetchAnotherApiOnResponseData()
                    .then(() => {
                        ...
                    })
                    .catch(() => {
                        ...
                    })
            })
            .catch((error) => {
                // handle api fail error
            })
    })
    .catch((error) => {
        // handle read file fail error
    })

If you see the above code, it works, but the code doesn't look structured. There is too much nesting. And as you all know:

maxresdefault.jpeg

What is async/await?

So, here comes the main part of the blog.

Now let us try to write the above piece of code using async-await:

Drumrolls🥁🥁....

const performAction = async => {
    const fileData = await readFile();
    const response = await fetchApi(fileData);
    await fetchAnotherApiOnResponseData(); 
}

Tada 🎉. The same code can be written in around 4 lines. The code looks cleaner, readable, and simpler.

Now let us try to understand what is happening:

Await keyword basically pauses the execution of the code till the promise is settled. And once the promise is settled the code executes further. Also, await keyword can only be used in async functions. To make a function async, you just have to add the async keyword at the beginning.

But there is one problem with the above code, it doesn't handle errors/rejections. Let us see that next.

Error handling in Async/await:

Error handling in async/await is very simple. You just have to enclose it in a try/catch block.

const performAction = async => {
    try {
        const fileData = await readFile();
        const response = await fetchApi(fileData);
        await fetchAnotherApiOnResponseData();
    } catch (error) {
        // any error/rejections in the above code will be caught here
    }
}

If any of the promises is rejected, it will stop the execution and jump directly to the catch block.


meme3.jpeg


Points to remember:

  1. Use await whenever the response expected is a promise.
  2. await keyword can only be used in async functions.

So in this blog post, we have seen:

  • What is async/await?
  • Its advantages over then/catch.
  • Error handling in async/await.
  • 2 keys points to remember.