Home > Net >  React Promise All Multiple APIs, Different Error Handling
React Promise All Multiple APIs, Different Error Handling

Time:11-22

I wanted to run different error handling with React Promise. Run APIs all at once to save time, and have different error handling statements for each API. How can this be done?

API 1 and 2 should have different error handlings, and each API should continue even if one fails.

Reference:

Fetch API requesting multiple get requests

Promise.all([
            fetch(api1).then(value => value.json()),
            fetch(api2).then(value => value.json())
            ])
            .then((value) => {
               console.log(value)
              //json response
            })
            .catch((err) => {
                console.log(err);
            });

CodePudding user response:

Promise.all is just wrapping up whatever promises you give it - so there's no reason you couldn't handle the errors separately for each one. For example, you could create a separate function for each of the fetches:

const fetchFromApi1 = async () => {
  try {
    const response = await fetch(api1);
    return response.json();

  } catch (err) {
    console.log('API 1 failed');

    // You have to re-throw here if you want the promise returned by
    // this function to be rejected
    throw err;
  }
};

const fetchFromApi2 = async () => {
  // ----- 8< -----
};

Then you can just combine them in your your Promise.all -

const fetchAllTheThings = async () => {
  try {
    const [response1, response2] = await Promise.all([
      fetchFromApi1(),
      fetchFromApi2(),
    ]);

  } catch (err) {
    // One of the promises was rejected
  }
};

Edit

If you want to know which promise failed at the point of calling, you're probably better off using allSettled -

const fetchAllTheThings = async () => {
  const [result1, result2] = await Promise.allSettled([
    fetchFromApi1(),
    fetchFromApi2(),
  ]);

  if (result1.status === 'rejected') {
    // Sad for promise 1
  }

  if (result2.status === 'rejected') {
    // Sad for promise 2
  }
};

CodePudding user response:

const p1 = new Promise((res, rej) => {
  setTimeout(() => {
    res("p1 success")
  }, 1000)
})
const p2 = new Promise((res, rej) => {
  setTimeout(() => {
    res("p2 success")
  }, 3000)
})
const p3 = new Promise((res, rej) => {
  setTimeout(() => {
    rej("p3 failed")
  }, 1000)
})
const p4 = new Promise((res, rej) => {
  setTimeout(() => {
    rej("p4 failed")
  }, 2000)
})

Promise.allSettled([p1, p2, p3, p4])
  .then(console.log)

  • Related