Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

203
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!