首页 > 解决方案 > 在循环中调用异步等待时出现语法错误

问题描述

我的 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")
            }

标签: javascriptnode.js

解决方案


每个等待的函数都必须是异步函数。包括传递给的那个forEach

emails.forEach(async (email) => {

或者,您可以通过使用简单的循环来避免创建迭代函数for of。这通常比使用forEach更受欢迎,因为它更简单一些并且不会创建任何新功能。

for (const email of emails) {
    //...
    var newEmail = await contact.simp_email(simp_email)
    //...
}

推荐阅读