Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Looping with Promises in JS

I am trying to run queries inside a for loop in nodejs and each iteration of the for loop runs one query. The queries are done with a "get()" method that returns a Promise. In my function (that contains this for loop), I am returning the promise returned by the get() method like so:

for(var i=0; i < productIds.length; i++) { return queryObject.get(productIds[i]).then(//handle result) }

but this returns after the first iteration and doesn't continue for the rest of the iterations. How do I solve this issue?

For context, I am using Parse's Cloud Functions.

like image 614
krishnakeshan Avatar asked Dec 31 '25 04:12

krishnakeshan


1 Answers

You have to build up a promise chain like so:

let chain = Promise.resolve();

for (i=0; i<1000; i++) {
   chain = chain.then(()=>queryObject.get(objectId))
}

chain.then(()=>{ /* do something once all queries have returned a result */})
like image 53
TLP Avatar answered Jan 01 '26 19:01

TLP



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!