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

标签 javascript promise fetch

我正在尝试使用 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

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

最佳答案

更改此:

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

对此:

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

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

关于javascript - 如何使用 Promise.allSettled 访问 fetch/http 调用的响应值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66288478/

相关文章:

javascript - 如何将 json POST 数据作为对象传递给 Web API 方法?

javascript - 在 JavaScript 间隔内等待

javascript - 将嵌套的 'for' 循环转换为 Promise,对于 Promise?嵌套 promise ?

reactjs - 通过 Reactjs 中的 axios 取消我的 POST 请求 promise

javascript - 离线时获取 "real"设备时间的策略

javascript - IE10 : getElementsByName() is not returning the elements that has same Id in IE10

使用标签名称从 Tumblr 获取所有帖子的 java 代码

javascript - Promise.all 中获取失败,未捕获错误

javascript - 将数组转换为对象+设置属性名称

javascript - promise 不发送任何数据。没有错误吗?