Monday, 11 November 2024

How to handle multiple promises

 To handle multiple promises in one call, you can use Promise.all, Promise.allSettled, Promise.any, or Promise.race depending on your requirements.

1. Using Promise.all

  • This method waits for all promises to resolve, or it rejects as soon as one promise rejects. It returns an array of resolved values if all promises succeed.

    const promise1 = fetch("https://api.example.com/data1");

    const promise2 = fetch("https://api.example.com/data2");

 

    Promise.all([promise1, promise2])

      .then((responses) => Promise.all(responses.map((res) => res.json())))

      .then((data) => {

        console.log("Data from all promises:", data);

      })

      .catch((error) => {

        console.error("One of the promises failed:", error);

      });

2. Using Promise.allSettled

  • Promise.allSettled waits for all promises to complete, regardless of whether they resolve or reject. It returns an array of objects with each promise's status ("fulfilled" or "rejected") and value or reason.

    const promise1 = fetch("https://api.example.com/data1");

    const promise2 = fetch("https://api.example.com/data2");

 

    Promise.allSettled([promise1, promise2])

      .then((results) => {

        results.forEach((result, index) => {

          if (result.status === "fulfilled") {

            console.log(`Promise ${index + 1} succeeded with:`, result.value);

          } else {

            console.error(`Promise ${index + 1} failed with:`, result.reason);

          }

        });

      });

3. Using Promise.any

  • Promise.any resolves as soon as any promise resolves (useful for fallback mechanisms) and rejects only if all promises reject.

    const promise1 = fetch("https://api.example.com/data1");

    const promise2 = fetch("https://api.example.com/data2");

 

    Promise.any([promise1, promise2])

      .then((firstResult) => firstResult.json())

      .then((data) => {

        console.log("First successful result:", data);

      })

      .catch((error) => {

        console.error("All promises failed:", error);

      });

4. Using Promise.race

  • Promise.race returns the result of the first promise that settles, whether it resolves or rejects. It’s often used for timeout functionality.

    const promise1 = fetch("https://api.example.com/data1");

    const promise2 = new Promise((_, reject) => setTimeout(() => reject("Timeout"),     5000)); // Rejects after 5 seconds

 

    Promise.race([promise1, promise2])

      .then((result) => result.json())

      .then((data) => {

        console.log("First promise to settle:", data);

      })

      .catch((error) => {

        console.error("Promise race failed:", error);

      });

Each of these methods provides different control over how promises are handled, so you can choose based on the behavior you need in your application.

 

No comments:

Post a Comment