DEV Community

Discussion on: for loop vs .map() for making multiple API calls

Collapse
 
zaquwa profile image
Quinn

Not really a fair comparison. Map is creating a new array of promises then asynchronously executing them. To do this with a for loop you would do something like this:

const todoIdList = [1, 2, 3, 4]
const promiseList = []

for (const id of todoIdList) {
const response = fetch(https://jsonplaceholder.typicode.com/todos/${id})
promiseList.push(response.json())
}

const responses = Promise.all(promiseList)

Collapse
 
askrishnapravin profile image
Krishna Pravin

This approach looks good. Pushing the promises into an array within for loop will achieve concurrency.
But when we have a need for more than one await inside the block, it will not work.
In the above code, response.json() won't work because response is a promise, it won't have json() method.