javascriptecmascript-6promise

only throw error if all API calls in Promise.all fail


Before starting an express server JS I want to make three API calls. If any one of them fails I just want to log an error, but if all three fail I want to throw an error and prevent the server from starting.

I have seen I can use Promise.all, but I am unsure how to handle the case if one fails. Using the code below if any fail the error will be thrown. How can I limit this to only occurring if all calls fail?

const fetchNames = async () => {
    try {
      await Promise.all([
        axios.get("./one.json"),
        axios.get("./two.json"),
        axios.get("./three.json")
      ]);
    } catch {
      throw Error("Promise failed");
    }
  };

Solution

  • If you don't need the fulfillment values, or need just any of them, Promise.any will work for this use case - it'll reject only if all Promises reject.

    const firstResolveValue = await Promise.any([
            axios.get("./one.json"),
            axios.get("./two.json"),
            axios.get("./three.json")
    ]);
    

    If you need all result values from the Promises that happen to fulfill, use Promise.allSettled.

    const settledResults = await Promise.allSettled([
        axios.get("./one.json"),
        axios.get("./two.json"),
        axios.get("./three.json")
    ]);
    const fulfilledResults = settledResults.filter(result => result.status === 'fulfilled');
    if (!fulfilledResults.length) {
        throw new Error();
    } else {
        // do stuff with fulfilledResults
    }