繁体   English   中英

只返回履行的承诺

[英]return only fulfilled promises

我对 api 做了很多请求。 我需要的是只返回履行的承诺,所以我可以在之后使用它们,使用 json() function。 经过一番谷歌搜索后,我现在有了这段代码,它似乎不起作用。 这样做的正确方法是什么?

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

我认为您想为此使用 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));

请参阅此以获取更多信息
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