JavaScript Closures for React :👈 👉:JavaScript Event Loop Behavior in React

JavaScript Promises and async/await in React

JavaScript Promises and async/await in React

1. Introduction

React applications frequently communicate with APIs to retrieve, save, update, or delete data.

These operations take time because they depend on external resources such as servers and databases. JavaScript handles these operations asynchronously so that the application can continue responding to user interactions.

Two important JavaScript concepts used for asynchronous programming are:

  • Promises
  • async/await

2. What Is Asynchronous JavaScript?

JavaScript normally executes statements one after another. However, some operations take time, such as fetching data from an API, reading files, waiting for a timer, or saving information to a server.

Instead of blocking the application while waiting, JavaScript can start these operations and continue executing other code.

console.log("First");
setTimeout(() => {
    console.log("Second");
}, 2000);
console.log("Third");

Output:

First
Third
Second

The setTimeout() operation runs asynchronously. JavaScript does not wait for it to finish before executing the next statement.

3. What Is a Promise?

A Promise is a JavaScript object that represents the eventual result of an asynchronous operation.

A Promise can be in one of three states:

  1. Pending: The operation is still in progress.
  2. Fulfilled: The operation completed successfully.
  3. Rejected: The operation failed.

A Promise eventually settles as either fulfilled or rejected.

Promise Example

const myPromise = new Promise((resolve, reject) => {
    const success = true;
    if (success) {
        resolve("Data loaded successfully");
    } else {
        reject("Something went wrong");
    }
});
myPromise
    .then((result) => {
        console.log(result);
    })
    .catch((error) => {
        console.error(error);
    });

Explanation:

  • resolve() indicates successful completion.
  • reject() indicates failure.
  • .then() handles successful completion.
  • .catch() handles rejection.

4. Understanding then(), catch() and finally()

These methods are commonly used to handle Promise results.

then()

Executes when a Promise is fulfilled.

fetch("/api/users")
    .then((response) => {
        return response.json();
    })
    .then((data) => {
        console.log(data);
    });

catch()

Handles errors and rejected Promises.

fetch("/api/users")
    .then((response) => response.json())
    .then((data) => {
        console.log(data);
    })
    .catch((error) => {
        console.error("Error:", error);
    });

finally()

Executes after the Promise settles, whether fulfilled or rejected. It is useful for cleanup operations, such as stopping a loading indicator.

fetch("/api/users")
    .then((response) => response.json())
    .then((data) => {
        console.log(data);
    })
    .catch((error) => {
        console.error(error);
    })
    .finally(() => {
        console.log("Request completed");
    });

5. What Is async/await?

async/await is a cleaner way to write asynchronous JavaScript code using Promises. It makes asynchronous code look similar to ordinary sequential code.

  • async declares an asynchronous function.
  • await pauses execution inside that async function until the awaited Promise settles.
  • When the Promise fulfills, await returns its result.
  • When the Promise rejects, await throws an error that can be handled using try/catch.

Example

async function getUsers() {
    const response = await fetch("/api/users");
    const data = await response.json();
    console.log(data);
}
getUsers();

The await keyword makes the function wait for each asynchronous operation before moving to the next statement. It does not block the entire JavaScript application.

6. Promise vs async/await

Both approaches use Promises internally. The difference is mainly how asynchronous code is written and organized.

Promise approachasync/await approach
Uses .then()Uses await
Uses .catch()Usually uses try/catch
Can create long chainsOften easier to read
Useful for chaining operationsUseful for sequential asynchronous logic
Directly works with Promise objectsBuilt on top of Promises

Promise Approach

function getUsers() {
    return fetch("/api/users")
        .then((response) => response.json())
        .then((data) => {
            console.log(data);
            return data;
        })
        .catch((error) => {
            console.error(error);
        });
}

async/await Approach

async function getUsers() {
    try {
        const response = await fetch("/api/users");
        const data = await response.json();
        console.log(data);
        return data;
    } catch (error) {
        console.error(error);
    }
}

Both approaches can perform the same asynchronous operation.

7. Using async/await in React

One of the most common uses of async/await in React is fetching data from an API.

Example: Fetch Users Using useEffect

import React, { useEffect, useState } from "react";
function Users() {
    const [users, setUsers] = useState([]);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState("");
    useEffect(() => {
        async function fetchUsers() {
            try {
                const response = await fetch("/api/users");
                if (!response.ok) {
                    throw new Error("Failed to fetch users");
                }
                const data = await response.json();
                setUsers(data);
            } catch (error) {
                setError(error.message);
            } finally {
                setLoading(false);
            }
        }
        fetchUsers();
    }, []);
    if (loading) {
        return <p>Loading users...</p>;
    }
    if (error) {
        return <p>Error: {error}</p>;
    }
    return (
        <div>
            <h2>User List</h2>
            <ul>
                {users.map((user) => (
                    <li key={user.id}>
                        {user.name}
                    </li>
                ))}
            </ul>
        </div>
    );
}
export default Users;

Explanation:

  1. useState stores users, loading status, and error information.
  2. useEffect starts the API request after the component renders.
  3. fetchUsers() is an asynchronous function.
  4. await fetch() waits for the HTTP response.
  5. await response.json() converts the response body into JavaScript data.
  6. setUsers() updates the component state.
  7. catch handles errors.
  8. finally stops the loading indicator.

The empty dependency array means the effect runs after the initial mount. In this example, cleanup for an in-flight request is not yet implemented; the next section shows how to handle it.

8. Why Can't We Directly Use async on useEffect?

The callback passed to useEffect should return either nothing or a cleanup function. However, an async function always returns a Promise.

Incorrect approach:

useEffect(async () => {
    const response = await fetch("/api/users");
    const data = await response.json();
    setUsers(data);
}, []);

This is incorrect because the effect callback returns a Promise instead of a cleanup function or nothing.

Correct approach:

useEffect(() => {
    async function fetchUsers() {
        const response = await fetch("/api/users");
        const data = await response.json();
        setUsers(data);
    }
    fetchUsers();
}, []);

You can also use an async immediately invoked function expression (IIFE):

useEffect(() => {
    (async () => {
        const response = await fetch("/api/users");
        const data = await response.json();
        setUsers(data);
    })();
}, []);

Both approaches are valid. A named inner function is often easier to read and maintain.

9. Handling API Errors Properly

An important point: fetch() does not automatically reject its Promise for HTTP error responses such as 404 or 500. You must check response.ok.

async function getUser() {
    try {
        const response = await fetch("/api/users/1");
        if (!response.ok) {
            throw new Error(
                `HTTP Error: ${response.status}`
            );
        }
        const user = await response.json();
        return user;
    } catch (error) {
        console.error("API Error:", error.message);
        throw error;
    }
}

Why check response.ok?

A server can return an HTTP 404 or 500 response while the fetch() Promise still fulfills. Checking response.ok ensures that unsuccessful HTTP responses are handled as errors by your application.

10. Handling Multiple API Calls

Sometimes a React component needs data from multiple APIs. There are two common approaches.

A. Sequential API Calls

Use this approach when the second API depends on the result of the first API.

async function getUserDetails() {
    const userResponse = await fetch("/api/users/1");
    if (!userResponse.ok) {
        throw new Error("Failed to fetch user");
    }
    const user = await userResponse.json();
    const ordersResponse = await fetch(
        `/api/users/${user.id}/orders`
    );
    if (!ordersResponse.ok) {
        throw new Error("Failed to fetch orders");
    }
    const orders = await ordersResponse.json();
    return {
        user,
        orders
    };
}

Here, the orders API requires the user ID returned by the first API.

B. Parallel API Calls Using Promise.all()

Use Promise.all() when multiple API calls are independent.

async function getDashboardData() {
    try {
        const [usersResponse, productsResponse] =
            await Promise.all([
                fetch("/api/users"),
                fetch("/api/products")
            ]);
        if (!usersResponse.ok || !productsResponse.ok) {
            throw new Error("Failed to fetch dashboard data");
        }
        const [users, products] = await Promise.all([
            usersResponse.json(),
            productsResponse.json()
        ]);
        return {
            users,
            products
        };
    } catch (error) {
        console.error(error);
        throw error;
    }
}

Promise.all() behavior:

  • Starts all supplied Promises together.
  • Waits until all Promises fulfill.
  • Returns their results in the original input order.
  • Rejects as soon as one of the Promises rejects.
  • Does not automatically cancel the other operations.

Other useful Promise methods:

MethodPurpose
Promise.all()Fulfills when all Promises fulfill; rejects if one rejects.
Promise.allSettled()Waits for every Promise to settle.
Promise.race()Settles with the first Promise to settle.
Promise.any()Fulfills with the first fulfilled Promise; rejects if all reject.

11. Avoiding Race Conditions and Cleaning Up API Requests

Consider a search box where users type quickly.

The application may send multiple API requests:

  • Request 1: Search for "Re".
  • Request 2: Search for "React".
  • Request 3: Search for "React Hooks".

If an older request finishes after a newer request, it might overwrite the latest search results. This is called a race condition.

One solution is AbortController, which allows an in-progress fetch request to be cancelled.

import { useEffect, useState } from "react";
function SearchUsers({ searchTerm }) {
    const [users, setUsers] = useState([]);
    useEffect(() => {
        if (!searchTerm) {
            setUsers([]);
            return;
        }
        const controller = new AbortController();
        async function search() {
            try {
                const response = await fetch(
                    `/api/users?search=${encodeURIComponent(searchTerm)}`,
                    {
                        signal: controller.signal
                    }
                );
                if (!response.ok) {
                    throw new Error("Search failed");
                }
                const data = await response.json();
                setUsers(data);
            } catch (error) {
                if (error.name !== "AbortError") {
                    console.error(error);
                }
            }
        }
        search();
        return () => {
            controller.abort();
        };
    }, [searchTerm]);
    return (
        <ul>
            {users.map((user) => (
                <li key={user.id}>{user.name}</li>
            ))}
        </ul>
    );
}

Explanation:

  • A new controller is created for each effect execution.
  • The request receives its abort signal.
  • When searchTerm changes or the component unmounts, the previous effect cleanup runs.
  • controller.abort() cancels the previous fetch request.
  • AbortError is ignored because cancellation is expected.

This helps prevent outdated requests from updating the component after a newer search has started.

12. Using async/await in Event Handlers

You can also use async/await when a user clicks a button or submits a form.

Example: Save User

import { useState } from "react";
function SaveUser() {
    const [saving, setSaving] = useState(false);
    const [message, setMessage] = useState("");
    async function handleSave() {
        setSaving(true);
        setMessage("");
        try {
            const response = await fetch("/api/users", {
                method: "POST",
                headers: {
                    "Content-Type": "application/json"
                },
                body: JSON.stringify({
                    name: "John"
                })
            });
            if (!response.ok) {
                throw new Error("Failed to save user");
            }
            setMessage("User saved successfully");
        } catch (error) {
            setMessage(error.message);
        } finally {
            setSaving(false);
        }
    }
    return (
        <div>
            <button onClick={handleSave} disabled={saving}>
                {saving ? "Saving..." : "Save User"}
            </button>
            <p>{message}</p>
        </div>
    );
}
export default SaveUser;

React supports asynchronous event handlers. Here, the button is disabled while the request is running to help prevent duplicate submissions.

13. Common Mistakes When Using Promises and async/await

Mistake 1: Forgetting await

Incorrect:

async function getUsers() {
    const data = fetch("/api/users");
    console.log(data);
}

The variable data contains a Promise, not the response.

Correct:

async function getUsers() {
    const response = await fetch("/api/users");
    const data = await response.json();
    console.log(data);
}

Mistake 2: Forgetting error handling

Incorrect:

async function getUsers() {
    const response = await fetch("/api/users");
    const data = await response.json();
    return data;
}

Correct:

async function getUsers() {
    try {
        const response = await fetch("/api/users");
        if (!response.ok) {
            throw new Error("Request failed");
        }
        return await response.json();
    } catch (error) {
        console.error(error);
        throw error;
    }
}

Mistake 3: Using async directly in useEffect

Incorrect:

useEffect(async () => {
    // API call
}, []);

Correct:

useEffect(() => {
    async function loadData() {
        // API call
    }
    loadData();
}, []);

Mistake 4: Waiting sequentially for independent APIs

Less efficient:

const users = await getUsers();
const products = await getProducts();

If both operations are independent, use:

const [users, products] = await Promise.all([
    getUsers(),
    getProducts()
]);

Mistake 5: Forgetting that fetch does not reject on HTTP errors

Incorrect:

const response = await fetch("/api/users");
const data = await response.json();

Correct:

const response = await fetch("/api/users");
if (!response.ok) {
    throw new Error("HTTP request failed");
}
const data = await response.json();

Mistake 6: Updating state after an outdated request

When component effects depend on changing values, clean up in-flight requests or otherwise guard against stale responses. Use AbortController where supported by the API.

Mistake 7: Not returning a Promise from a function

Incorrect:

function getUsers() {
    fetch("/api/users").then((response) => response.json());
}

Correct:

function getUsers() {
    return fetch("/api/users")
        .then((response) => response.json());
}

Returning the Promise allows callers to use .then() or await.

14. Best Practices in React

  1. Use async/await when it makes asynchronous code easier to read.
  2. Always handle errors using try/catch or Promise rejection handlers.
  3. Check response.ok when using fetch().
  4. Do not make the useEffect callback itself async.
  5. Use Promise.all() for independent API requests.
  6. Use sequential await when one request depends on another.
  7. Clean up in-flight requests when effects are restarted or components unmount.
  8. Keep loading, success, and error states clear in the UI.
  9. Avoid unnecessary duplicate API requests.
  10. For larger applications, consider a data-fetching library such as TanStack Query or SWR.

15. When to Use Promises and async/await

ScenarioRecommended approach
Fetching API dataasync/await
Saving form dataasync/await
Calling multiple independent APIsPromise.all()
Waiting for dependent API callsSequential async/await
Handling several independent outcomesPromise.allSettled()
Managing request cancellationAbortController
Simple Promise chainingthen() and catch()

16. Interview Questions and Answers

Q1. What is a Promise in JavaScript?

A Promise is an object representing the eventual success or failure of an asynchronous operation. It can be pending, fulfilled, or rejected.

Q2. What are the three states of a Promise?

  • Pending
  • Fulfilled
  • Rejected

Q3. What is async/await?

async/await is syntax built on Promises that makes asynchronous JavaScript code easier to read and maintain.

Q4. What is the difference between then() and await?

.then() attaches a callback to a Promise. await pauses execution inside an async function until the Promise settles, returning its value or throwing its rejection reason.

Q5. Why can't we use async directly in useEffect?

An async function always returns a Promise, but useEffect expects its callback to return either nothing or a cleanup function. Therefore, define and call an inner async function instead.

Q6. What is Promise.all()?

Promise.all() takes multiple Promises and fulfills with an array of their results when all fulfill. It rejects if any supplied Promise rejects.

Q7. What is the difference between Promise.all() and Promise.allSettled()?

Promise.all() rejects when any Promise rejects. Promise.allSettled() waits for all Promises and provides the fulfilled or rejected result of each one.

Q8. Does await block the entire application?

No. await pauses only the execution of the surrounding async function. Other JavaScript tasks and user interactions can continue.

Q9. Does fetch() throw an error for a 404 response?

No. A 404 or 500 HTTP response normally fulfills the fetch Promise. Check response.ok and throw an error when the response is unsuccessful.

Q10. What is AbortController?

AbortController is a browser API that can cancel supported asynchronous operations, including fetch requests. It is useful for cleaning up requests in React effects.

Q11. Can an event handler in React be async?

Yes. React event handlers can be asynchronous and can use await to handle API calls, form submissions, and other asynchronous operations.

Q12. What is a race condition in API calls?

A race condition occurs when multiple asynchronous operations finish in an unexpected order. An older request may overwrite the result of a newer request. Request cancellation or response-order checks can help prevent this.

17. Final Summary

  • Promise: Represents the eventual result of an asynchronous operation.
  • then(): Handles successful Promise completion.
  • catch(): Handles Promise rejection.
  • finally(): Executes after a Promise settles.
  • async: Declares an asynchronous function.
  • await: Waits for a Promise inside an async function.
  • Promise.all(): Runs independent asynchronous operations together and waits for all to fulfill.
  • AbortController: Helps cancel in-progress fetch requests.
  • useEffect: Commonly used to synchronize a React component with external systems, including API requests.

Remember: Promises and async/await are JavaScript features, not React-specific features. React applications use them to handle asynchronous operations such as API calls, form submissions, and data loading.

🔙
JavaScript Closures for React :👈 👉:JavaScript Event Loop Behavior in React

Comments and Discussion