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

205
Visualizações
How to wait on promises in loop before returning?

I'm working on a project where I need to loop through multiple values and then count the number of items in a database that match those values. The results are then returned.

Here is the code I am wanting to run:

var types = config.deviceTypes

for(const type of types)
{
  db.find(
    {
      selector:
      {
        type: {$eq: type.name}
      }
    }
  )
  .then(results => type.count = results.docs.length)
}

return types

Running this however returns types without having made any modifications to the count since this function is being run asynchronously. I have tried making the following modification to use await:

var types = config.deviceTypes

for(const type of types)
{
  var results = await db.find(
    {
      selector:
      {
        type: {$eq: type.name}
      }
    }
  )
  type.count = results.docs.length
}

return types

However this gives the error: "SyntaxError: await is only valid in async function"

I am using PouchDB on Node 14.17.0

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

0

"SyntaxError: await is only valid in async function"

The error can be fixed by making sure you're doing this in an async function.


async function foo() {
  var types = config.deviceTypes

  for(const type of types)
  {
    var results = await db.find(
      {
        selector:
        {
          type: {$eq: type.name}
        }
      }
    )
    type.count = results.docs.length
  }

  return types;

}
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