【问题标题】:How do I access the response value for a fetch/http call using Promise.allSettled?如何使用 Promise.allSettled 访问 fetch/http 调用的响应值?
【发布时间】:2021-05-23 02:07:26
【问题描述】:

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

我在这里缺少什么?提前感谢您的帮助

【问题讨论】:

    标签: javascript promise fetch


    【解决方案1】:

    改变这个:

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

    到这里:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-23
      • 1970-01-01
      • 2021-08-30
      • 1970-01-01
      相关资源
      最近更新 更多