在firebase中发送通知前node js查询mysql

zqdjd7g9  于 2021-06-21  发布在  Mysql
关注(0)|答案(1)|浏览(437)

请告诉我如何查询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);
  });

我经常遇到以下错误:

ar5n3qh5

ar5n3qh51#

根据文件 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);
              });
            }
          });
        }
      });
    });

  });

相关问题