gpt4 book ai didi

javascript - 在循环中调用 async wait 时出现语法错误

转载 作者:行者123 更新时间:2023-12-02 21:09:44 24 4
gpt4 key购买 nike

我的 NodeJs 应用程序中有一个路由,它接受一个发布请求,然后使用等待检索一些数据。我的函数中的第一个等待工作正常,但当我用等待调用另一个函数时它会提示。我用 >>>> 标记了导致问题的函数

语法错误: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)
//...
}

关于javascript - 在循环中调用 async wait 时出现语法错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61128549/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com