Search code examples
javascriptnode.jsecmascript-6es6-promise

Async/Await with for loop | await is only valid in async function


Below is the code I am trying to run:

async function verifyExistingUsers(db, users) {
    return new Promise((resolve, reject) => {

       var companies = []
       for (const [index, user] of users.entries()) {

           let company = await getUserCompany(db, user)
           companies.push(company) 

           if (index === users.length-1) {
               resolve(companies)
           }
       }
   })
}

async function getUserCompany(db, user) {
    return new Promise((resolve, reject) => {
        db.Company.findAll({
            where: {
                id: user.id,
            }
        }).then(company => {
            resolve(company)
        })
    }).catch(error => {
        reject()
    })
}

I keep getting the following error:

let companies = await getUserCompany(db, user)
                ^^^^^
SyntaxError: await is only valid in async function

I can't use forEach because I need to await.

New to javascript. What am I doing wrong?


Solution

  • As a follow-up to my comment: verifyExistingUsers has no reason to 'return new promise'. Node will wrap your return statement in a promise on its own because the function is 'async'.

    The original error here is because you effectively cannot use await in the anonymous, non-async function, ((resolve, reject) => {}).

    Instead of returning a new promise, you will just return the variable you want when you are done pushing data into the array. By doing so and declaring the function as 'async', Node will wrap your return value in a promise that you await somewhere else.

    async function verifyExistingUsers(db, users) {
           var companies = []
           for (const [index, user] of users.entries()) {
    
               let company = await getUserCompany(db, user)
               companies.push(company) 
    
               if (index === users.length-1) {
                   return companies; //effectively returns a promise that resolves to companies
               }
           }
    }