-1

I know this question is not the first asked here but I tried to work with other answers but my code is not working as expected. I have a Promise.all where I have multiple fetch. The result of the fetch I turn into a json and then goon. When everything is done it should print "done" and of course more code to come. However, what happens is, that "done" is printed right away and then one by one the result of the fetches come in.

Here is my code:

  Promise.all(selectedTypes.map((type) => {
    let body = {
      selectedScreenshot: type,
      dataUrl: dataUrl
    };
    fetch(URL, {
      method: 'POST',
      body: JSON.stringify(body),
      credentials: 'same-origin',
    })
    .then(resp => {
      console.log(resp.json()); //  this is done one by one as the results come in
      console.log('next');
    })
    }
  )).then(text => {
    console.log('done'); // this should be printed last, is printed first
  })

What am I doing wrong?

threxx
  • 1,213
  • 1
  • 31
  • 59

1 Answers1

1

You need to return the fetch and return some result in fetch().then() and here is some helpful information and examples for Promise.all

selectedTypes = ["https://jsonplaceholder.typicode.com/todos/1", "https://jsonplaceholder.typicode.com/todos/2"]; // My example
Promise.all(selectedTypes.map((type) => {
    let body = {
        //selectedScreenshot: type,
        //dataUrl: dataUrl
    };
    var URL = type;
    //You need to return the fetch
    return fetch(URL, {
        // method: 'POST',
        // body: JSON.stringify(body),
    }).then((resp) => resp.json()) // Transform the data into json
            .then(function (data) {
                console.log(data); //  this is done one by one as the results come in
                console.log('next');
                // you need to return the data
                return data;
            });
}
)).then(text => {
    text.forEach(function (item) {
        console.log('FROM PROMISE ALL');
        console.log(item);
    });
    console.log('done'); // this should be printed last, is printed first
});

I have added some json links just for example and commented everything that is not declared in your question

angel.bonev
  • 2,154
  • 3
  • 20
  • 30
  • 1
    Do you need more examples ? Simply put if you dont return anything the promise is resolved `Promise.all([function () { 2 + 2; }]).then(data => { console.log("resolved"); });` – angel.bonev Oct 15 '19 at 11:11