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.
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() .
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.
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.
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 #.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With