async func(){
try{
let iter=[1,2,3]
for (i of iter){
let result=await someFunc()
pool.query("some query",arrWithResult)
}
}catch(err){console.log(err)}
}
Here, the loop waits for await. But I don't want that. I need the result and sql query to be executed in sequence but the loop should continue without waiting. I also need value of current i when executing query. Otherwise, I would just push these promises into array and do Promise.all(arr)
async func(){
try{
let iter=[1,2,3]
for (i of iter){
someFunc().then(body=>{pool.query("some query",arrWithResult).catch(err=>err)
}
}catch(err){console.log(err)}
}
Is this okay? I also thought of making then part async but should I add another try catch block?
So, what is best way for this? Or should i go for then/catch. When doing Promise.all, the value of iter gets lost.
Maybe I'm underthinking it (or you're overthinking it), but why would you not just refactor into another async function that does what needs to be done on each iteration of the loop, and then Promise.all() the list of returned promises to let them resolve?
Something like this:
async func f1() {
const iter = [ 1, 2, 3 ] ;
return await Promise.all( iter.map(f2) );
}
async func f2(i) {
const result = await someFunc() ;
return await pool.query( "some query" , arrWithResult );
}
The the caller then just needs to say ...
const responses = await f1();
```
Don't use an iterator var for this - this is a job for Array.map()
Promise.all([1,2,3].map(i => someFunc().then(body => pool.query("some query",arrWithResult).catch(err=>err));