7

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?

7
  • 2
    You finally copied your whole code and now we can effectively see your problem :). You have no reason to return a promise in the first function. Remove the return new Promise from verifyExistingUsers, everything will happen synchronously in it and you can just return companies; instead. Commented Feb 23, 2019 at 3:24
  • Lots of stuff. No need to return a promise from async function, just return the value. That will also fix the specific error: you're awaiting in the callback to the promise constructor which is not async. Commented Feb 23, 2019 at 3:28
  • 2
    @mad ward not sync, its still async. But yeah, no need to explicitly call the promise constructor. Commented Feb 23, 2019 at 3:29
  • You are right, I meant to say the code will look as if it were synchronous without blocking the event loop, but couldn't quite put my finger on the phrasing. Commented Feb 23, 2019 at 3:39
  • @MadWard why did you delete your answer? Commented Feb 23, 2019 at 3:49

2 Answers 2

5

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
           }
       }
}
Sign up to request clarification or add additional context in comments.

Comments

1

I've countered the same issue if i understand your question correctly this is the solution you need, and you can also use it in loops, i hope this help you, if this is not your answer just tell me to update my answer

const AsyncFuncion = async () => {
  let interval = 2000;
  const delayPromise = (data, delayDuration) => {
    return new Promise((resolve) => {
      setTimeout(() => {
            // here you can do your operations on db
          resolve();
      }, delayDuration)
    });
  };


  try {
    const userData = // the data you want from db or you can use http request to get that data
    const promises = userData.map((data, index) => delayPromise(data, index * interval));
    await Promise.all(promises);
    setTimeout(function(){
      console.log('done') // after 10 minitues it'll repeate it self you can disable it also
      AsyncFuncion()
    }, 1000 * 60 * 10)
  } catch (e) {
    console.error('AsyncFuncion', e);
  }
}

AsyncFuncion();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.