简体   繁体   English

只返回履行的承诺

[英]return only fulfilled promises

I do a lot of requests to api.我对 api 做了很多请求。 What i need is to return only fulfilled promises, so i can use them after, with json() function.我需要的是只返回履行的承诺,所以我可以在之后使用它们,使用 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我认为您想为此使用 Promise.allSettled ,它为传递给它的每个 promise 提供状态,无论它是否已满或失败,下面是您更新的代码

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 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/allSettled

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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