Home > OS >  How to wait on promises in loop before returning?
How to wait on promises in loop before returning?

Time:10-15

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

CodePudding user response:

"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;

}
  • Related