I am sending multiple requests to a API say "myapi/id". My ids could range from [0..10000]. Because sending all ids at once is very expensive, I would like to send in slice wait for it to be fetched and then send the next slice.
Here is the code I am using:
async function getSlice(data) {
let promises = []
data.map((key) => {
promises.push(fetch("myapi/"+key)
.then(res => res.json())
.then((result) => console.log(result))) //I want to store the result in an array
}
await Promise.all(promises)
}
function getAll(data) {
for(let i=0; i<= data.length; i+=10) {
getSlice(data.slice(i,i+10));
//I want to wait for the previous slice to complete before requesting for the next slice
}
}
getAll(ids)
However, the requests are being sent asynchronously/there is no waiting happening. I was wondering if there is an error in my code/ if there is any way to send multiple requests using a for loop and wait for them to complete before sending the next requests.
Promise.allif you would like to call an API sequentially? (Other than saving data in an array)Promise.map? Instead of looping throughdata, map (a massaged version of )dataso that you canawait Promise.all(...)that, too. Unless you need this to be synchronous (i.e. getSlice 0 needs to finish before getSlice 10 happens) in which case you may want to rethink why you're using async at all.