【问题标题】:(..).then is not a function ,firebase cloud functions(..).then 不是函数,firebase 云函数
【发布时间】:2017-10-07 12:12:26
【问题描述】:

我正在尝试异步运行一个函数。但它会引发错误。以下是我的代码:

exports.listenForNotificationRequests = functions.database.ref('/notificationRequests/{pushId}')
    .onWrite(event => {
       const requestId = event.data.val();
       var sentTo = requestId.sentTo;
       var senderIds =  sentTo.split(",");
     //  var senderTokens = "";

       var payload = {
                data: {
                  title: requestId.username,
                  message:  requestId.message,
                  sentFrom: requestId.sentFrom
                }
        };

       getSenderIds(senderIds).then(function(senderTokens){
            console.log("SenderTokens", senderTokens);
            admin.messaging().sendToDevice(senderTokens.split(","), payload)
                    .then(function(response) {
                      console.log("Successfully sent message:", response);
                    })
                    .catch(function(error) {
                      console.log("Error sending message:", error);
            });

       });

});

function getSenderIds(senderIds){
    var senderTokens = "";
    senderIds.forEach(function (snapshot){
                var ref = admin.database().ref("users/"+snapshot+"/token");
                console.log("refernce", snapshot);
                ref.once("value", function(querySnapshot2) {
                         var snapVal = querySnapshot2.val();
                         console.log("Token", snapVal);
                         senderTokens = senderTokens+","+snapVal;
                });
    });
    return senderTokens;
}

在执行时会抛出异常:

TypeError: getSenderIds(...).then is not a function
    at exports.listenForNotificationRequests.functions.database.ref.onWrite.event (/user_code/index.js:20:39)
    at /user_code/node_modules/firebase-functions/lib/cloud-functions.js:35:20
    at process._tickDomainCallback (internal/process/next_tick.js:129:7)

我尝试了多种解决方案,但都没有用。这里有人能指出我犯了什么错误吗?或者是否有其他解决方案?

【问题讨论】:

    标签: node.js firebase firebase-cloud-messaging


    【解决方案1】:

    你不能返回一个函数,你需要返回一个事件或者什么都不返回。

    【讨论】:

      【解决方案2】:

      要使用 then() 你的 getSenderIds() 应该返回一个 Promise 而此时它返回一个字符串。

      ref.once() 确实返回了一个 Promise。您可以做的是使 senderTokens 成为一个数组,并为每次迭代将 ref.once() 推送到该数组。

      因为 ref.once() 返回一个 Promise,这使得 senderTokens 成为一个包含每个查询结果的 Promise 数组。然后你可以返回 Promise.all(senderTokens) read more about Promise.all here

      然后在 then (function(senderTokens){}) 里面做 to String 处理 通过在 senderTokens 数组的每个项目上调用 .val() 来阻止。

      【讨论】:

      • 你也可以减少承诺
      • 谢谢,真的很有帮助。
      猜你喜欢
      • 1970-01-01
      • 2020-03-14
      • 2020-11-05
      • 2020-06-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-03
      • 2017-11-15
      相关资源
      最近更新 更多