Async/Await 用 for 循环 | await 只在 async 函数中有效

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

下面是我正在尝试的代码 运行:

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()
    })
}

我不断收到以下错误:

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

我不能使用 forEach 因为我需要 await.

javascript 的新手。我做错了什么?

作为我评论的后续:verifyExistingUsers 没有理由 'return new promise'。 Node 会将您的 return 语句包装在自己的 promise 中,因为该函数是 'async'.

这里的原始错误是因为您实际上不能在匿名、非异步函数 ((resolve, reject) => {}).

中使用 await

而不是 return 一个新的承诺,当你完成将数据推入数组时,你将 return 你想要的变量。通过这样做并将函数声明为 'async',Node 会将您的 return 值包装在您在其他地方等待的承诺中。

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
           }
       }
}

如果我正确理解你的问题,我已经解决了同样的问题,这就是你需要的解决方案,你也可以在循环中使用它,我希望这对你有帮助,如果这不是你的答案,请告诉我更新我的回答

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();