繁体   English   中英

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

[英]How do I access the response value for a fetch/http call using Promise.allSettled?

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

控制台日志 output: 在此处输入图像描述

我在这里想念什么? 在此先感谢您的帮助

改变这个:

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

对此:

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

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

暂无
暂无

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

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