获取语​​法错误:await仅在node9

时间:2018-03-10 05:38:00

标签: node.js asynchronous google-cloud-firestore

在云函数中,我使用async / await函数,因为要在序列中执行。但我在第

行收到错误
  

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

     

SyntaxError:await仅在异步函数中有效。

     

云功能

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

我在异步函数中使用了await函数。但仍然收到错误

1 个答案:

答案 0 :(得分:2)

违规行位于.forEach()回调函数内,该函数未声明为异步。

您还应该知道await也不会暂停.forEach()循环迭代,即使您将回调声明为async也是如此。循环的所有其他迭代将继续运行。您可以切换到实际的for循环,然后循环将暂停await

此外,这看起来有点奇怪:

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

admin.messaging().sendToDevice(Token, payload))是否会返回一系列承诺?如果没有,那么这也不是Promise.all()的正确使用。我们必须知道admin.messaging().sendToDevice(Token, payload)返回了什么,以便进一步帮助它。