Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
122
rated 0 times [  125] [ 3]  / answers: 1 / hits: 9286  / 4 Years ago, tue, april 28, 2020, 12:00:00

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.


More From » node.js

 Answers
9

You need to use await before async function if you want to wait for it for
finish



async function getAll(data) {
for(let i=0; i<= data.length; i+=10) {
await getSlice(data.slice(i,i+10));
}
}

getAll(ids).then(()=>console.log('all data processed')).catch(err=>/*handle
error*/)


Ps. i think that you need to use Promise.allSettled method instead of Promise.all. If one of your request will return an error, you will get all chunk failed if you will use Promise.all. Promise.allSettled will wait for all results - positive or negative.
Anothe old sollution is to use catch method for each request, like



 promises.push(fetch(myapi/+key)
.then(res => res.json())
.then((result) => console.log(result))
.catch((err)=>{/*handle error if needed*/; return null})


And after that you will have some nulls in array with results


[#3990] Sunday, April 26, 2020, 4 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jaelyn

Total Points: 619
Total Questions: 102
Total Answers: 104

Location: Honduras
Member since Sun, Dec 26, 2021
2 Years ago
;