javascript - 未处理的PromiseRejection警告: Unhandled promise rejection (rejection id: 1): ReferenceError: registrationTokens is not defined

标签 javascript google-cloud-firestore

当我尝试使用 Firestore 获取数据时,出现上述错误 - 我正在尝试从数据库检索 token ,以便可以发送消息:

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

最佳答案

您已在 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 是异步执行的,因此您需要等待结果出现。

关于javascript - 未处理的PromiseRejection警告: Unhandled promise rejection (rejection id: 1): ReferenceError: registrationTokens is not defined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55611807/

相关文章:

flutter - 如何在flutter中获取文档id

AngularFire - 将两个具有相同 pushId 项目的 FireStore 集合组合起来

google-cloud-firestore - Firestores 10 000 次写入/秒限制

javascript - 将 div 提取为包含 CSS 类的 HTML

javascript - Chrome 扩展脚本不工作

javascript - AngularJS ng :submit on 'enter' key

javascript - 哪个在 JavaScript String 中效率更高

javascript - CSS 饼图切片无法悬停

android - 获取可与 Cloud Firestore 配合使用的简单应用

firebase - 无法将 flutter web 应用程序链接到 firebase 项目/无限加载