我尝试使用云功能在 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/