Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

214
Views
How do I handle promises inside loop inside async function in javascript?
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.

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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();
```
about 4 years ago · Juan Pablo Isaza Report

0

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));
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!