1. Overview

I hope you guys are familiar with the basics of Promise in Nodejs. If you have seen Promise’s article of this series, there are some drawbacks to promises. It can be overcome by async/await. In this article, I will cover some of the basic topics of async/await.

2. Async/Await in Nodejs

Async/await is syntactical sugar to work with promises in the simplest manner.

Async: Indicates function will always return a promise instead of returning a result.

Await: Wait for a promise to resolve or reject. It works only inside the async function.

Let’s try it with some examples.

2.1.1 Without await operator

function sayHello(message) {
    return Promise.resolve(message);
}
console.log(sayHello("Hello from Java developer zone"));

Output:

As you see in the output, sayHello() returns resolved promise. But without await, you won’t get any data. Let’s use await keyword and see the magic 😉

2.1.2 With await operator

function sayHello(message) {
    return Promise.resolve(message);
}
let message = await sayHello("Hello from Java developer zone");
console.log(message);

oops.. 🙁 You will get Error something like this,

SyntaxError: await is only valid in async function

As we discussed earlier, await is only allowed inside the async function.

2.1.3 With async/await

Now, we use both keywords to get the expected output.

function sayHello(message) {
    return Promise.resolve(message);
}
async function main() {
    let message = await sayHello("Hello from Java developer zone");
    console.log(message);
}
main();

Output:

You got your message wrapped in promise here.

3. Error handling

As we have seen in promises, we can’t handle both synchronous and asynchronous errors in the same try/catch block. let’s take a look.

Function for converting a string to a JSON object,

function parseJsonString(jsonStr) {
    return new Promise((resolve, reject) => {
        let obj = JSON.parse(jsonStr);
        resolve(obj);
    });
}

3.1 Using promises

3.1.1 To handle synchronous error

Pass invalid string in JSON.parse(). It will throw an error and .catch() block of try will execute. Here, the JSON object is passed as an argument.

try {
    JSON.parse({ lang: 'Java', name: 'Developer zone' });
    pareJsonString('{"lang":"Java", "name":"Developer zone"}')
        .then(data => {
            console.log("Parsed data :", data);
        }).catch(err => {
            console.log("Rejected :", err);
        });
} catch (err) { //this catch block will execute
    console.log(err);
}

SyntaxError: Unexpected token o in JSON at position 1

3.1.2 To handle asynchronous error

Try to pass an erroneous string in parseJsonString(). It will throw an error and will be caught by the catch() block of then().

try {
    // JSON.parse({ lang: 'Java', name: 'Developer zone' });
    parseJsonString('{"lang":"Java" "name":"Developer zone"}')
        .then(data => {
            console.log("Parsed data :", data);
        }).catch(err => { //this catch block will execute
            console.log("Rejected :", err);
        });
} catch (err) {
    console.log(err);
}

Rejected : SyntaxError: Unexpected string in JSON at position 15

As we can see, there are multiple catch blocks to handle errors in promises. It’s time to see a simple way to handle it in async/await.

3.2 Using async/await

3.2.1 To handle synchronous error

async function main() {
    try {
        JSON.parse({ lang: 'Java', name: 'Developer zone' });
        let jsonObj = await parseJsonString('{"lang":"Java", "name":"Developer zone"}');
        console.log("Parsed data :", jsonObj);
    } catch (err) {
        console.log("Rejected :", err);
    }
}
main();

Rejected : SyntaxError: Unexpected token o in JSON at position 1

3.2.2 To handle asynchronous error

async function main() {
    try {
        // JSON.parse({ lang: 'Java', name: 'Developer zone' });
        let jsonObj = await parseJsonString('{"lang":"Java" "name":"Developer zone"}');
        console.log("Parsed data :", jsonObj);
    } catch (err) {
        console.log("Rejected :", err);
    }
}
main();

Rejected : SyntaxError: Unexpected string in JSON at position 15

We can handle both types of errors within the same catch block in case of async/await.

4. Why async/await?

  • Easy to read and write asynchronous code.
  • Easy error handling.

5. Conclusion

In the end, we may get confused about what to use? Well, Promise is a better option to use instead of using async/await in case of running multiple parallel jobs. So far in this blog, we learned about the async/await which is an alternative for a promise in Nodejs, how and where to use async/await, synchronous and asynchronous error handling with async/await.

6. Reference

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *