UnhandledPromiseRejectionWarning:未处理的承诺拒绝(拒绝ID:1):ReferenceError:registrationTokens未定义

时间:2019-04-10 11:47:40

标签: javascript google-cloud-firestore

当我尝试使用Firestore来获取数据时出现上述错误-我试图从数据库中检索令牌,以便发送消息:

exports.getUsers = functions.https.onRequest(async (req, res) => {
    db.collection("users")
        .get()
        .then(snapshot => {
            let registrationTokens = [];
            snapshot.forEach(doc => {
                let id = doc.id;

                registrationTokens.push(id);
            });
        });

    console.log(registrationTokens);

    const message = {
        data: { title: "Testing", body: "Test" },
        tokens: registrationTokens
    };

    messaging.sendMulticast(message).then(response => {
        console.log(response.successCount + " messages were sent successfully");
    });
});

1 个答案:

答案 0 :(得分:1)

您已在promise中声明了registrationTokens,因此在promise之外不可见:

exports.getUsers = functions.https.onRequest(async (req, res) => {

    db.collection("users")
            .get()
            .then(snapshot => {
                 let registrationTokens = [];  
                 snapshot.forEach(doc => {
                    let id = doc.id;

                    registrationTokens.push(id);
                });
                console.log(registrationTokens);

               // process the tokens
               const message = {
                 data: { title: "Testing", body: "Test" },
                 tokens: registrationTokens
               };

               messaging.sendMulticast(message).then(response => {
                   console.log(response.successCount + " messages were sent successfully");
              });


        });
    });

您需要记住,promise是异步执行的,因此您需要等待结果出现。