WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

JavaScript · Intermediate · question 32 of 100

How do you handle asynchronous operations with async/await?

📕 Buy this interview preparation book: 100 JavaScript questions & answers — PDF + EPUB for $5

Asynchronous operations are a fundamental part of JavaScript programming, and they are often used to make network requests or perform other time-consuming tasks without blocking the main thread of the application. In the past, asynchronous operations were typically handled with callback functions or promises, but the introduction of async and await in ECMAScript 2017 has made it easier to write asynchronous code that looks and behaves like synchronous code.

Here’s an example of an asynchronous function that fetches data from an API using fetch() and returns a promise:

    function fetchData() {
        return fetch('https://jsonplaceholder.typicode.com/todos/1')
        .then(response => response.json())
        .then(data => console.log(data))
        .catch(error => console.error(error));
    }

In this example, fetchData() returns a promise that resolves with the JSON data from the API. This promise is handled with .then() and .catch() methods, which are used to log the data to the console or log any errors that occur.

Here’s the same example using async and await:

    async function fetchData() {
        try {
            const response = await fetch('https://jsonplaceholder.typicode.com/todos/1');
            const data = await response.json();
            console.log(data);
        } catch (error) {
            console.error(error);
        }
    }

In this example, fetchData() is defined as an async function, which means it returns a promise that resolves with the value of the function. The try block contains the asynchronous code, which is executed using the await keyword. The await keyword waits for the asynchronous operation to complete and then returns the result, which can be assigned to a variable (response and data in this case). Any errors that occur are caught in the catch block.

Using async and await can make asynchronous code easier to read and write, especially for complex operations that involve multiple promises or callback functions. However, it’s important to remember that await can only be used inside an async function, and that asynchronous operations can still block the main thread of the application if they are not properly optimized.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic JavaScript interview — then scores it.
📞 Practice JavaScript — free 15 min
📕 Buy this interview preparation book: 100 JavaScript questions & answers — PDF + EPUB for $5

All 100 JavaScript questions · All topics