如何使用 Promise.allSettled 访问 fetch/http 调用的响应值?

问题描述 投票:0回答:2

我正在尝试使用 Promise.allSettled 调用 3 个 url,并在全部完成后处理结果。但是,我似乎无法访问 JSON 格式的响应值。这是我的代码:

let urlList = ['http...', 'http...', 'http...'];

let fetches = urlList.map(url => fetch(url));
Promise.allSettled(fetches)
    .then((results) => { // (*)

        results.forEach((result, num) => {

            if (result.status == "fulfilled") {
                //result.value is a response object and I cannot seem to access the response.body or the actual text/json value of the response
                // in chrome developer tools, I can see the results I want, just can't seem to read them here
                console.log(result.value);
            }
            else if (result.status == "rejected") {
                console.log(`Failed Calling: ${urls[num]}\n\treason: ${result.reason}`);
            }

        });

        //call other method with combined results...
    })
    .catch((err) => {
        alert(err);
    });

console.log输出: enter image description here

我在这里缺少什么?预先感谢您的帮助

javascript promise fetch
2个回答
6
投票

更改此:

let fetches = urlList.map(url => fetch(url));

对此:

let fetches = urlList.map(url => fetch(url).then(res => res.json()));

这样,您的

Promise.allSettled()
将为您提供一系列承诺,这些承诺将解析为您的最终值,而不仅仅是响应标头对象,因此您的
result.value
属性将是每个承诺的最终值。


0
投票
let fetches = urlList.map((url) => fetch(url));
Promise.allSettled(fetches)
  .then((results) => {
    // --> async function
    results.forEach(async (result, num) => {
      if (result.status === "fulfilled") {
        // --> await the json() result
        console.log(await result.value.json());
      } else if (result.status == "rejected") {
        // --> handle rejections here
        console.error(
          `Failed Calling: ${fetches[num]}\n\treason: ${result.reason}`
        );
      }
    });
  })
  .catch((err) => {
    console.error(err);
  });
© www.soinside.com 2019 - 2024. All rights reserved.