最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - AsyncAwait with for loop | await is only valid in async function - Stack Overflow

programmeradmin1浏览0评论

Below is the code I am trying to run:

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

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

           let pany = await getUserCompany(db, user)
           panies.push(pany) 

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

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

I keep getting the following error:

let panies = 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?

Below is the code I am trying to run:

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

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

           let pany = await getUserCompany(db, user)
           panies.push(pany) 

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

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

I keep getting the following error:

let panies = 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?

Share Improve this question asked Feb 23, 2019 at 3:19 user1107173user1107173 10.8k17 gold badges75 silver badges121 bronze badges 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 panies; instead. – Azami 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. – Jared Smith 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. – Jared Smith 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. – Azami Commented Feb 23, 2019 at 3:39
  • @MadWard why did you delete your answer? – user1107173 Commented Feb 23, 2019 at 3:49
 |  Show 2 more ments

2 Answers 2

Reset to default 5

As a follow-up to my ment: 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 panies = []
       for (const [index, user] of users.entries()) {

           let pany = await getUserCompany(db, user)
           panies.push(pany) 

           if (index === users.length-1) {
               return panies; //effectively returns a promise that resolves to panies
           }
       }
}

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();
发布评论

评论列表(0)

  1. 暂无评论