Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

204
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda