简体   繁体   中英

return only fulfilled promises

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())))

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM