javascript - OneSignal 和 Firebase 云函数 - 返回未定义的预期 Promise 或值

标签 javascript google-cloud-functions onesignal

我尝试使用云功能在 Firestore 中创建新的聊天消息文档时触发推送通知。

我还使用 OneSignal,如下面的代码所示。但是,云函数一直提示我的函数没有返回 promise 或值,并且我不确定在这里返回什么函数。我应该返回哪里以及返回什么?

exports.newChatNotification = functions.firestore.
document('channels/{userId}/thread/{docId}').
onCreate((snap, context) => {

  // Get the values of the newly created document
  const newValue = snap.data();

  // Access the "content" field
  const content = newValue.content;
  console.log(content);

  // Access the "userID" field
  const userID = newValue.userID;
  console.log(userID);

  const docId = context.params.docId;
  console.log(docId);

  // OneSignal notification sending
  var sendNotification = function(data) {
    var headers = {
      "Content-Type": "application/json; charset=utf-8",
      "Authorization": "{Authorization token}"
    };

    var options = {
      host: "onesignal.com",
      port: 443,
      path: "/api/v1/notifications",
      method: "POST",
      headers: headers
    };

    var https = require('https');
    var req = https.request(options, function(res) {  
      res.on('data', function(data) {
        console.log("Response:");
        console.log(JSON.parse(data));
      });
    });

    req.on('error', function(e) {
      console.log("ERROR:");
      console.log(e);
    });

    req.write(JSON.stringify(data));
    req.end();
  };

  var message = { 
    app_id: "APP_ID",
    contents: {"en": content},
    include_player_ids: ["PLAYER_ID_1", "PLAYER_ID_2"]
  };

  sendNotification(message);

});

最佳答案

Cloud Functions 要求您返回一个 promise ,该 promise 会在函数中的所有异步工作完成时解析。这就是您告诉 Cloud Functions 可以安全地清理和终止该函数的方式。这不是可选的 - 如果您没有像这样正确返回 promise ,工作可能永远不会完成,并且您的代码将根本无法工作。

我建议reading the documentation关于这一点,请务必了解 JavaScript Promise 的工作原理。

关于javascript - OneSignal 和 Firebase 云函数 - 返回未定义的预期 Promise 或值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59911799/

相关文章:

javascript - 如何在 firestore 中创建一个数组?

c# - 在 C# 或 JS 中更改我的 css 样式时加载其他页面

node.js - Firebase数据库如何防止并发读取?

javascript - Firebase 功能 - 在上传到存储时调整大小并覆盖现有图像

php - 如何使用苹果推送通知 p12 证书文件通过代码设置 ios 平台?

javascript - bootstrap-modal.js 在 Bootstrap 3 中损坏

javascript - 是否可以在特定条件下注册点击事件?

javascript - Firebase 的云功能陷入无限循环

ionic-framework - Ionic - Onesignal - 在handleNotificationReceived上不更新 View

flutter - 从 flutter 中发送一个信号通知