【问题标题】:Node Js Query MySql Before Sending Notification in FirebaseNode Js在Firebase中发送通知之前查询MySql
【发布时间】:2018-06-09 16:21:27
【问题描述】:

请问在向设备发送通知之前如何查询 MySql 并等待结果。这是我的代码

exports.pushNotification = functions.database
  .ref("/messages")
  .onWrite((change, context) => {
    console.log("Push notification event triggered");
    const payload = {
      notification: {
        title: "Test Message",
        body: "Welcome to Node",
        sound: "default"
      },
      data: {
        title: "Test Message",
        message: "Welcome to Node"
      }
    };
    /* Create an options object that contains the time to live for the notification and the priority. */
    const options = {
      priority: "high",
      timeToLive: 60 * 60 * 24 //24 hours
    };
    var token = new Promise(function(resolve, reject) {
      con.connect(function(err) {
        if (err) {
          reject(err);
        } else {
          con.query("SELECT fcm_token FROM users WHERE id = 24", function(
            err,
            result,
            fields
          ) {
            if (err) {
              reject(err);
            } else {
              token = result[0].fcm_token;
              resolve(token);
            }
          });
        }
      });
    });
    console.log("Token : " + token);
    return admin.messaging().sendToDevice(token, payload, options);
  });

我不断收到以下错误:

【问题讨论】:

    标签: mysql node.js firebase google-cloud-functions firebase-admin


    【解决方案1】:

    根据documentationsendToDevice不接受promise作为参数。因此,您必须改为使用已解析的令牌调用 sendToDevice,然后才能解析/拒绝。

    exports.pushNotification = functions.database
      .ref("/messages")
      .onWrite((change, context) => {
        console.log("Push notification event triggered");
        ...
        return new Promise(function(resolve, reject) {
          con.connect(function(err) {
            if (err) {
              reject(err);
            } else {
              con.query("SELECT fcm_token FROM users WHERE id = 24", function(
                err,
                result,
                fields
              ) {
                if (err) {
                  reject(err);
                } else {
                  token = result[0].fcm_token;
                  console.log("Token : " + token);
                  admin.messaging().sendToDevice(token, payload, options).then(function() {
                    resolve();
                  }).catch(function(err) {
                    reject(err);
                  });
                }
              });
            }
          });
        });
    
      });
    

    【讨论】:

    • 感谢您的回复,我得到了错误:每个 then() 都应该返回一个值或抛出,所以我添加了 return true 和 return null 在不同的时间但我得到了一个类似于上面的错误
    猜你喜欢
    • 2015-05-30
    • 1970-01-01
    • 1970-01-01
    • 2018-10-29
    • 1970-01-01
    • 2018-05-08
    • 1970-01-01
    • 2020-11-12
    • 1970-01-01
    相关资源
    最近更新 更多