Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

216
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda