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

186
Visualizações
How to call a function after an asynchronous for-loop?

I have the following for-loop:

for await (const account of accountCursor) {
  const newAccount = handleAccount(account, migrationService);
  try {
    await migrationService.accountService.create(newAccount);
  } catch (error) {
    console.log('Unable to create account');
    throw Error(error)
  }
}

handleRelatedAccounts();  // call once the for-loop has completed

Once it has finished, I want to call another function. Since it is asynchronous, how can I call the function after the for-loop has finished, not during?

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Assuming you want to run the function whether or not an error is caught and re-thrown in your loop, you can just wrap the entire loop in a try...finally statement: below is an example. (If not, I'm not sure why you are re-throwing the caught error and what kind of behavior you expect.)

try {
  for await (const account of accountCursor) {
    const newAccount = handleAccount(account, migrationService);
    try {
      await migrationService.accountService.create(newAccount);
    } catch (error) {
      console.log('Unable to create account');
      throw Error(error)
    }
  }
}
finally {
  handleRelatedAccounts();  // call once the for-loop has completed
}
about 4 years ago · Juan Pablo Isaza Relatório

0

You do not have to do anything. handleRelatedAccounts(); always run after the loop. await means it will wait until the premise is finished to do the next code. Because you throw Error(error), it will stop the execution when there is an exception, handleRelatedAccounts(); will be never hit in this case.

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