return only fulfilled promises

Viewed 787

I do a lot of requests to api. What i need is to return only fulfilled promises, so i can use them after, with json() function. After some googling i have this code right now and it's seems like doesn't work. What is the correct way of doing so?

async function requestAPI(items) {
        var requests = items.map(item => fetch(url).catch(e => e))
        return Promise.all(requests);
      }

getUrls()
  .then(result => requestAPI(result))
  .then(result => Promise.all(result.map(v => v.json())))
1 Answers

I think you want to use Promise.allSettled for this which gives status for each promise that is passed to it whether it got fullfilled or failed, below is your updated code

async function requestAPI(items) {
    var requests = items.map(item => fetch(url));
    return Promise.allSettled(requests);
}

function getOnlyFulFilled(allResults) {
    const fulfilledResult = [];
    allResults.forEach((result) => {
        if (result.status === "fulfilled") {
            fulfilledResult.push(result.value);
        }
    });
    return fulfilledResult;
}

getUrls()
    .then(result => requestAPI(result))
    .then((allResults) => {
        return getOnlyFulFilled(allResults);
    })
    .then(result => Promise.allSettled(result.map(v => v.json())))
    .then((allResult) => getOnlyFulFilled(allResults));

please refer this for more info
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/allSettled

Related