1

I am getting this issue at the moment:

Parsing error: Unexpected token db. It's flagging up at the getMember line. I have used this line of code before and it's fine. Here is the code:

                    clubMemCheck.forEach(doc => {

                        if (doc.data().dropletUserId) {
                            let addUserId = doc.data().dropletUserId
                            let getMember = await db.collection('users').doc(addUserId).get()

                            var userIdM = getMember.data().userId
                            var phone = getMember.data().phone
                            var avatar = getMember.data().avatar
                            var firstName = getMember.data().firstName
                            var lastName = getMember.data().lastName
                            var screenName = getMember.data().screenName

                            var userItem = {userId: userIdM, phone: phone, avatar: avatar, firstName: firstName, lastName: lastName, screenName: screenName}
                            clubContacts.push(userItem)
                        }

                    });

EDIT: Seems ok when I take out "Await" but that could potentially make the values below it return as nothing.

Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
Darryl
  • 49
  • 5

1 Answers1

3

Your code is trying to use await inside a function that has not been declared async. The function here is the inner anonymous function that you passed to forEach. If you have async at a higher scope, that doesn't apply - await can only be used in the innermost function where it appears.

If you want to use await within a forEach loop, there are resources that give some alternatives:

Or, if you can convert the forEach into a for-loop, that will eliminate the inner function passed to forEach.

Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
  • 1
    Thanks for the reply. I changed it so that it was clubMemCheck.forEach(async doc => { And await started working, however sometimes it returned 0 records and sometimes it contained 1. There is defo 1 in there. So not sure what's happening. – Darryl May 21 '20 at 16:29
  • Right, you can't just put await on the inner function. The links I provided explain why that doesn't work the way you expect. The forEach loop will not "wait" for the inner awaits to complete. It will just iterate over all the returned promises from the async function. Consider using the advice of the linked answers to collect all the promises into an array and await them with Promise.all(). – Doug Stevenson May 21 '20 at 16:31