I am attempting to use fetch inside a loop (something like the pseudo code below) and I know that the responses may come back in a different order to that in which they were asked. That would be fine so long as I know what the value of ctr was when the fetch request was originally made but I can not fathom a way of getting that information passed from the original fetch call to the processing of the response.
All the example snippets I see about using fetch in loops seem to suggest that you add commands to wait for each fetch call to finish before doing the next one but I presume this would be slower (correct me if you think I’m wrong in that regard).
for (let ctr = 0;ctr < 10;ctr++)
{
fetch(URL_OF_SOME_API,fetch_options)
.then((response) => response.json())
.then(function (data_returned_by_API)
{
// do something with data_returned_by_API and ctr
});
}
2
Answers
You can wrap the internal of the loop inside of an IIFE passing in
ctr
as an argument, e.g.:Or, you can use
Promise.all
, like this:Your code already works as intended because of how
let
works when its variable is used in closures.var
doesn’t workFor more information, you can check out What is the difference between "let" and "var"?