Problems with Promise.all

Viewed 155

I have to get back to this forum for help because I can't still make a 'Promise.all' work!

First, I have this function, which is supposed to return a promise:

const myFetch = (a, b) => {
    var url;
    // some stuff bulding 'url' using a and b
    fetch(url).then(response => {
        return response.json();
    }
})

The idea is that the above function returns a promise, whose value, once resolved, is the json object. I have checked that the json is actually valid. If I replace the "return ..." line with the line below I actually get a valid json:

response.json().then(res=> console.log(res))

Second, I have this for loop, after which I expect to have an array of promises:

promises = [];
for (...){
    // some other stuff
    promises.push(myFetch(a, b))
}

Eventually I execute this code:

Promise.all(promises)
.then(responses => { // <=== Here I get all "undefined"
    responses.forEach(response => {
        console.log(response);// <=== Here I get all "undefined"
    });
    // some other stuff that I can do only after all fetches are complete
})

I expect the .then portion to be executed only once all promises are resolved, and also expect "responses" to be a list of all the json responses from the individual promises above. Still, I get a string of "undefined". The impression is that the portion of code within .then is running even though the promises are not yet resolved.

What did I do wrong? How can I be sure to have all the json objects from the individual fetches before proceeding? (note, I cannot use await/async). Thanks

1 Answers

You need to return the promise from the fetch call, otherwise the promise chain will be broken, once you do this, all should play nice!

Something like so should work:

const myFetch = (a, b) => {
    var url;
    // some stuff bulding 'url' using a and b
    return fetch(url).then(response => {
        return response.json();
    })
};

A snippet example:

const myFetch = (url, a, b) => {
  return fetch(url).then(response => {
    return response.json();
  })
};

function testMyFetch() {
    promises = [];
    for(let i = 0; i < 5; i++) {
        promises.push(myFetch("https://jsonplaceholder.typicode.com/users/" + (i+1)));
    }
    Promise.all(promises).then(result => console.log("Promise.all result:", result));
}
testMyFetch();

Related