Async/Await in JavaScript

Posted on January 17, 2023
javascripttypescriptasyncawait

Async/await is a way to handle asynchronous code in JavaScript. It allows you to write asynchronous code that looks and behaves like synchronous code. The **async ** keyword is used to define an asynchronous function and the await keyword is used inside that function to wait for a promise to resolve before continuing execution. This makes it easier to write and reason about asynchronous code, as it eliminates the need for callback functions and the "callback hell" that can result from nested callbacks.

Here is an example of using async/await in JavaScript to fetch some data from a remote API:

async function getData() {
    try {
        const response = await fetch('https://example.com/data');
        const data = await response.json();
        console.log(data);
    } catch (error) {
        console.error(error);
    }
}


getData();

In this example, the getData function is defined as async which allows the use of the await keyword inside it. The await keyword is used to wait for the promise returned by the fetch function to resolve. Once the promise resolves and the data is received, it is logged to the console. If an error occurs, it is caught and logged to the console using a catch block.

It's important to note that the await statement can only be used inside an async function. And the function that calls the async function should be awaited or use .then() to handle the returned promise

Here are a few more examples of using async/await in JavaScript:

Making multiple requests in parallel

async function getData() {
    const data1 = await fetch('https://example.com/data1').then(res => res.json());
    const data2 = await fetch('https://example.com/data2').then(res => res.json());
    const data3 = await fetch('https://example.com/data3').then(res => res.json());
    console.log(data1, data2, data3);
}


getData();

In this example, the getData function makes three requests to different URLs in parallel using await keyword. Once all the promises have been resolved, the data is logged into the console.

Sequentially making requests

async function getData() {
    const data1 = await fetch('https://example.com/data1').then(res => res.json());
    console.log(data1);
    const data2 = await fetch('https://example.com/data2').then(res => res.json());
    console.log(data2);
    const data3 = await fetch('https://example.com/data3').then(res => res.json());
    console.log(data3);
}


getData();

In this example, the getData function makes three requests to different URLs one after the other. Each request is awaited before the next request is made.

Handling errors

async function getData() {
    try {
        const data = await fetch('https://example.com/data').then(res => res.json());
        console.log(data);
    } catch (error) {
        console.error(error);
    }
}


getData();

In this example, the getData function makes a request to a remote API and handles any errors that may occur using a try-catch block. If an error occurs, it is logged to the console using the console.error() function.

Note that in the above examples, fetch() is used to make requests. fetch() returns a promise which can be awaited, but it does not reject on HTTP error status, instead, it will resolve with the HTTP error status. So it is important to check the status of the response with res.ok or res.status and throw an error if necessary.

Troubleshooting async/await code in JavaScript can be challenging, but here are a few tips that can help:

Check for syntax errors: Make sure that the async keyword is used before defining an asynchronous function and the await keyword is used inside that function before calling an asynchronous operation.

Check for promise rejection: Make sure that the function or value that you are awaiting is actually returning a promise. Also ensure that the promise is rejected if an error occurs, and not just resolved with an error object.

Check for missing await: Make sure that you are awaiting the result of an asynchronous operation before trying to use it. If you forget to await a promise, the code will continue to execute before the promise has been resolved, which can lead to unexpected behavior.

Check for unhandled errors: Make sure that you are using a try-catch block or a .catch() method to handle rejected promises and any other errors that may occur.

Check for missing .then() or .catch(): Make sure that you are returning the promise or chaining .then() or .catch() method to handle the resolved value or error.

Check for non-async function: Make sure that the function you are trying to call using await is defined as async.

Use debugging tools: Use browser developer tools or a JavaScript debugging tool like the Node.js debugger statement or a tool like node-inspector to step through your code and see what's happening at each step.

Printing variable: If you are not sure what's going wrong, try adding console.log() statements to your code to see the values of variables at different points in the execution.

By following these tips, you should be able to identify and fix any issues with your async/await code in JavaScript.

In conclusion, async/await is a powerful tool for handling asynchronous code in JavaScript. It allows you to write clean and readable code that is

There is good article Comparing Callbacks, Promises and Async Await in TypeScript from John Papa

Thanks for reading!


Posted on January 17, 2023
Profile Picture

Arun Yadav

Software Architect | Full Stack Web Developer | Cloud/Containers

Subscribe
to our Newsletter

Signup for our weekly newsletter to get the latest news, articles and update in your inbox.