NoSoup4you
NoSoup4you

Reputation: 668

SyntaxError when calling async await in Loop

I have a route in my NodeJs app which takes a post request and then retrieves some data with await. The first await in my function works fine but then it complains when i call another function with await. I marked the function which causes the issue with >>>>

SyntaxError: await is only valid in async function

Has this error to do with the forEach Loop and if so how can i fix that

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

Upvotes: 0

Views: 167

Answers (1)

Alex Wayne
Alex Wayne

Reputation: 187034

Every function that awaits, must be an async function. Including the one passed to forEach.

emails.forEach(async (email) => {

Alternatively, you could avoid creating an iteration function by using a simple for of loop. This is usually preferred to using the forEach since it's a bit simpler and doesn't create any new functions.

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

Upvotes: 2

Related Questions