javascript - 在循环中调用异步等待时出现语法错误
问题描述
我的 NodeJs 应用程序中有一条路由,它接受一个 post 请求,然后用 await 检索一些数据。我的函数中的第一个等待工作正常,但是当我用等待调用另一个函数时它会抱怨。我用>>>>标记了导致问题的函数
SyntaxError: await 仅在异步函数中有效
此错误与 forEach 循环有关,如果是,我该如何解决
farmRoutes.post('/bulkemail/:farmid', async(req, res) => {
try{
const farmid = req.params.farmid
// Check if we have an Emails Array
if (typeof req.body.emails != 'undefined' && req.body.emails instanceof Array ){
// Assign Emails Array from Body to emails
const emails = req.body.emails
// get the current Emails Array from Farm Doc
let oldEmail = await couch.getSubDoc('contacts', farmid ,'emails')
// Loop thru all emails in the new Array
emails.forEach((email) => {
console.log(email)
// Check if the email is curently already in the Farm Doc
var data = _.find(oldEmail, function(emailItem){ return emailItem.address == email; });
var index =_.indexOf(oldEmail,data);
if (index > -1) {
// Email already Exists will not be created
console.log("Email already in the List")
} else {
// if not in current Farm create new Email object and add to the oldEmail Array
>>>>>var newEmail = await contact.simp_email(simp_email)
// Upsert the updated Email Arra to farm Doc
var success = await cb.insertArrayItem(req.bucket, farmid, "emails", newEmail )
console.log(success)
}
})
} else {
console.log("we have no new emails")
}
解决方案
每个等待的函数都必须是异步函数。包括传递给的那个forEach
。
emails.forEach(async (email) => {
或者,您可以通过使用简单的循环来避免创建迭代函数for of
。这通常比使用forEach
更受欢迎,因为它更简单一些并且不会创建任何新功能。
for (const email of emails) {
//...
var newEmail = await contact.simp_email(simp_email)
//...
}
推荐阅读
- assembly - 有没有办法从 C64 的 Kick Assembler 中的宏访问全局常量
- html - 如何对齐导航栏上的所有元素?好像有点移位
- python - 如何在 python 上使用 selenium 修改/发送密钥到谷歌文档?
- c++ - C++ 默认值初始化随输入输出流而变化
- windows - 使用 PowerShell 将 .reg 文件与 Windows 注册表合并
- next.js - 如何从 NextJs 中的 dom 中删除 __NEXT_DATA__?
- python - 如何在 Python 中循环和更新变量
- spring-boot - 具有 cosmos 托管标识的 Spring Boot 应用程序
- typescript - 如何使用带有类型化架构签名的猫鼬别名
- c - 如何安全地将 unsigned long int 转换为 unsigned int?