节点Js在Firebase中发送通知之前查询MySql

时间:2018-06-09 16:21:27

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

请如何在向设备发送通知之前查询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);
  });

我一直收到以下错误:

enter image description here

1 个答案:

答案 0 :(得分:0)

根据documentation sendToDevice不承诺作为参数。因此,您必须使用已解析的令牌调用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);
              });
            }
          });
        }
      });
    });

  });