我正在尝试使用 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);
});
我在这里缺少什么?预先感谢您的帮助
最佳答案
更改此:
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/