catalins.tech with Gatsby

Making Promises Better With Async/Await πŸ”₯βŒ›

2020 Apr 19th

Today you learn how to work with promises in a more beautiful way. I do not know about you, but I am not a fan of those chains when working with promises. In my opinion, using async/await makes the code more readable and cleaner.

WHAT IS ASYNC/AWAIT ❔

Async/Await is built on top of promises, and it allows us to write asynchronous code more comfortably. It is just a new way of writing asynchronous code, besides promises and callbacks.

The power of Async/Await is that it makes the code look more organized, familiar and cleaner. It makes it look more “synchronous” too. Keep reading, and by the end of the article, you will agree with me.

THE USUAL PROMISE πŸ€ͺ

Let’s see an example of a promise in JavaScript:

const data = (url) => {
  return fetch(url)
    .then(response => {
        if (response.status == 200) {
            return response.json();
        } else {
            throw new Error(response.status);
        }
    });
};

Probably it looks familiar to you. Now, let’s see the same code re-written using async/await.

const data = async url => {
    try {
        const response = await fetch(url);
        
        if (response.status != 200) {
            throw new Error(response.status);
        }
        
        const responseData = await response.json();
        
        return responseData;
    } catch (err) {
        // Failed to fetch the data
        throw new Error(err);
    }
};

Which one do you prefer? In my opinion, it is clearer to understand what happens in the code when using async/await.

OK, OK. BUT WHAT IS HAPPENING BEHIND THE SCENES? πŸ€”

The first thing you need to notice is that we are using the keyword async in the method header. What does that mean? It means that the function always returns a promise. The keyword await only works if you specify the keyword async in the method header.

From the above statements, we can infer two other things:

  1. We cannot use await in a “normal” function. A “normal” function means any function that does not have the async keyword in the header.
  2. We cannot use the await keyword outside a function. We always have to wrap the await in an async function.

OK. How about that await thing? The keyword await makes the code wait until the promise is settled/rejected, and once it is resolved/rejected, it returns the result/error. Until the promise is settled, the engine can perform other things like executing other scripts. This is as far as I am going into asynchronous code in this article.

In the example above, the code stops at const response = await fetch(url); and continues only after the promise is resolved. That is, once the URL is “fetched”. The constant response gets assigned whatever that URL returns. After that, the code resumes.

CAN’T LIE. IT LOOKS BETTER. WHAT ARE THE OTHER BENEFITS? πŸ€”

BETTER ERROR HANDLING

First of all, we can handle the synchronous code and asynchronous code in the same construct. As a result, it provides better error handling. If there is an error in resolving the promise, the control jumps to the catch block to handle the error. Have a look at the second code snippet from above.

You can even wrap multiple promises in the same try block, and the code catches the errors from all promises, not only from one. It also tells you where the error occurred, in which promise.

BETTER CODE

I think I have said it already too many times, but it allows us to write clear and better code. Compare the two code snippets and come with your conclusion. You can see clearly what happens in the code, and understand it quicker and better.

This is an advantage which is not that obvious when having just a few lines of code. But once you start writing a lot of code, it helps a lot.

CONDITIONALS

Compare the two code snippets and decide where is the if statement clearer. Is it the first or the second snippet? Of course, the second one.

Bear in mind that the first code snippet using the classic promise is a simple one. Imagine that you have four or more if statements. It quickly gets out of hand.

Async/await makes everything more comfortable to read and understand.

CONCLUSION 🏁

What should you remember from this article?

  • Adding async to your method header, you always return a promise. Besides that, it allows you to use the await keyword. Therefore you can wait until a promise is resolved.
  • Makes the code more explicit, easier to understand, and more concise.
  • Using the await keyword, you block the code from executing until the promise is resolved or rejected.
  • When the promise cannot settle, it generates an exception.

PS: If you spot any mistakes, do correct me in the comments, please! πŸ™‚

Donation ❀️

Support my work! β€οΈπŸ™

Do you like my articles? Do you like my tweets? Do you like my work? ❀️

From now on you can support me by donating any amount you want! πŸ™

❗to donate more than $1.00, replace digit 1 with how much you want to donate ❗

$1.00