Lahari Areti
Lahari Areti

Reputation: 637

getting syntax error : await is only valid in async function in node9

In cloud functions, I used async/await functions because to execute in the sequence. But I am getting an error at the line

const response = await admin.messaging().sendToDevice(Token, payload) at

SyntaxError: await is only valid in async function.

Cloud Functions

const functions = require('firebase-functions');
const Firestore = require('@google-cloud/firestore');
const firestore = new Firestore();
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
var async = require('asyncawait/async');
var await = require('asyncawait/await');
const db = admin.firestore();
exports.splitting = functions.firestore
    .document('deyaPayUsers/{authid}/Split/{authid1}/SentInvitations/{autoid}') // Here the path is is triggereing
    .onWrite(async (event) => {
        try {
            const responses = [];
            var id = event.params.authid; //here we get the authid of the user who triggeres.
            var dbref = db.collection('deyaPayUsers').doc(id);
            var sendername;
            var doc = await dbref.get();

            if (!doc.exists) {
                console.log("No Such Document");
            } else {
                console.log('Document data of the firstname', doc.data().FirstName);
                sendername = doc.data().FirstName;
            }

            console.log(id);
            var id1 = event.params.authid1;
            var splitid = event.params.autoid;
            console.log("laha" + sendername);
            var document = event.data.data();
            var phoneNumber = [];
            //In loop
            for (var k in document) { // this line says about looping the document to get the phonenumber field in all the invites
                phoneNumber.push(document[k].PhoneNumber); // All the phonenumbers are stored in the phoneNumber array.
            }
            console.log("The json data is " + phoneNumber);
            var ph1 = document.Invite1.PhoneNumber; //It  gets the single user phoneumber in Invite1
            var amount = document.Invite1.Amount; //It gets the amount of the single user in invite1 in integer
            var a = amount.toString(); // It is used to convert the Integer amount into String
            console.log(a);
            console.log(document);
            console.log(ph1);
            var deyaPay = db.collection("deyaPayUsers"); // This path is user profile path to query with phonenumber
            for (var k in document) { // here It is the loop in a document to get the phonenumber
                var p = document[k].PhoneNumber; // here we get the phonenumber for every loop in invite and stored in p variable
                var am = document[k].Amount; // we get the amount of that invite
                var ams = am.toString(); // converting integer amount into string
                console.log("AMount of the user" + ams);
                let snapshot = await deyaPay.where('PhoneNumber', '==', p) // This line says that checking the user proile PhoneNumber field and the document phonenumber which is stored in p variable.
                    .get();
                snapshot.forEach(doc => { // It loops all the documnets whether the PhoneNumbers are matching with user profiles phonenumber
                    console.log(doc.id, " => ", doc.data()); // If matches it prints the doc id and the user data
                    var userData = doc.data(); //Here we get the doc data of that matched phonenumber
                    var userId = doc.id; // here it we get the id of the Matched profile
                    var FirstName = userData.FirstName;
                    console.log(FirstName);
                    var LastName = userData.LastName;
                    console.log(FirstName);
                    var FullName = FirstName + LastName;
                    console.log(FullName);
                    var Token = userData.FCMToken; // we need to take that fcm token to send the notification
                    console.log(userId);
                    console.log("FCM Token for that phoneNumber" + Token);
                    console.log(userData.PhoneNumber);
                    console.log(ph1 + "Exist In DB");
                    var msg = FirstName + " " + "requested you to pay $" + ams;
                    console.log("total notification is" + msg);
                    let payload = { //This is for sending notification message
                        notification: {
                            title: "Message",
                            body: msg,
                            sound: "default",

                        },
                        'data': { // these is the data it calls in the messagereceived method
                            'Name': sendername,
                            'Amount': ams
                        }
                    };
                    console.log(payload);
                    const response = await Promise.all(admin.messaging().sendToDevice(Token, payload));
                    console.info("Successfully sent notification")
                    responses.push(response);
                });
            };
            return responses; //here
        } catch (error) {
            console.info("error", error)
        }
    });

I have used the await function inside the async function. but still am getting error

Upvotes: 1

Views: 2508

Answers (1)

jfriend00
jfriend00

Reputation: 707386

The offending line is inside a .forEach() callback function that is NOT declared as async.

You should also know that await will not pause a .forEach() loop iteration either, even if you declare the callback as async. All the other iterations of the loop will continue to run. You could switch to an actual for loop, then the loop would pause with await.


Also, this looks a bit odd:

 Promise.all(admin.messaging().sendToDevice(Token, payload))

Does admin.messaging().sendToDevice(Token, payload)) return an array of promises? If not, then this is not a proper use of Promise.all() either. We would have to know what admin.messaging().sendToDevice(Token, payload) does return in order to help any further with that.

Upvotes: 3

Related Questions