Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use fetch within a for-loop, wait for results and then console.log it

i have this problem: i want to make multiple fetch calls within a for-loop. The number of calls depend on the user input (in my example i have three). How can i make it loop through all the fetch requests and then console.log the number off calls?

function getPosts(){

  let url = ["https://www.freecodecamp.org", "https://www.test.de/, http://www.test2.com"];
  let array = new Array;

  for (let i = 0; i < url.length; i++) {
    console.log(url[i]);
    fetch(url[i])
    .then(res => {return res.text(); })
    .then(res => {
            let reg = /\<meta name="description" content\=\"(.+?)\"/;
            res = res.match(reg);
            array.push(res);
            console.log(res);
          }
    )
    .catch(status, err => {return console.log(status, err);})
  }
  console.log (array.length);
  }

It console.logs 0 instead of 3, cause it doesn't wait for all the promises to be resolved. How can i make it to console.log 3? If you know a solution, please help me out.

like image 327
Timo Hoehn Avatar asked Jun 24 '18 18:06

Timo Hoehn


People also ask

How do I log responses in Fetch?

fetch() returns a Response object and not something that has already been parsed for you. You have to call . json() on it to get the response parsed by JSON. parse() .

How do you loop API calls?

We can branch and loop across API requests with the help of setNextRequest() function. This function is used to set the request to be executed next. This function takes one argument, i.e., the name of the request, which will execute next. In the above example, "My API" is the name of the request.

How does fetch work in Javascript?

The fetch() method takes one mandatory argument, the path to the resource you want to fetch. It returns a Promise that resolves to the Response to that request — as soon as the server responds with headers — even if the server response is an HTTP error status.


1 Answers

You can't call console.log(array.length) until after the promises are all done. So why not something like this?

let url = ["https://www.freecodecamp.org", "https://www.test.de/, http://www.test2.com"];
  let array = new Array;
  var fetches = [];
  for (let i = 0; i < url.length; i++) {
    console.log(url[i]);
    fetches.push(
      fetch(url[i])
      .then(res => {return res.text(); })
      .then(res => {
            let reg = /\<meta name="description" content\=\"(.+?)\"/;
            res = res.match(reg);
            array.push(res);
            console.log(res);
          }
      )
      .catch(status, err => {return console.log(status, err);})
    );
  }
  Promise.all(fetches).then(function() {
    console.log (array.length);
  });
  }

Promise.all waits for all the fetches to finish, THEN it'll print the #.

like image 111
Josh Avatar answered Oct 07 '22 14:10

Josh