javascriptpromisefetch

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


I'm trying to use Promise.allSettled to call 3 urls and process the results when all are finished. However, I cannot seem to access the value of the responses, which are JSON. Here is my code:

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 output: enter image description here

What am I missing here? Thanks in advance for the help


Solution

  • Change this:

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

    to this:

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

    That way your Promise.allSettled() will give you an array of promises that resolve to your final value, not just to the response headers object so your result.value property will be the final value for each promise.