我想自动实现推送通知,并且我使用了 javascript (node.js),但出现了此错误
Function returned undefined, expected Promise or value
我不是 Node js 开发人员,我是一名 Flutter 开发人员,我不知道什么是 Promise。
这是我的代码:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
var notificationMessageData;
exports.fcmTester = functions.firestore.document('posts/{postID}').onCreate((snapshot , context) => {
notificationMessageData = snapshot.data();
admin.firestore().collection('pushTokens').get().then(async (snapshot) => {
var tokens = [];
if (snapshot.empty) {
console.log('No Devices');
} else {
for (var token of snapshot.docs) {
tokens.push(token.data().tokenID);
}
var payload = {
"notification": {
"title": "from" + notificationMessageData.writer,
"body": "from" + notificationMessageData.name,
"sound": "default"
},
"data": {
"sendername": notificationMessageData.writer,
"message": notificationMessageData.name
}
}
return await admin.messaging().sendToDevice(tokens , payload).then((response) => {
console.log('nice');
}).catch((err) => {
console.log(err);
})
}
})
})
一切都很顺利,我上传它没有任何问题,但是当将文档添加到帖子集合时,它会在日志中输出上述错误。
我创建了一个用户注册表单,并注册了用户并将他们的 token ID 放入名为 PushTokens 的集合中,然后为该集合内的每个用户发送通知,但这不起作用。
最佳答案
您的代码中有两个问题:
- 您不会返回异步 Firebase 方法(
get()
和sendToDevice()
)返回的 promise ; - 您混淆了
async/await
与then()
的使用方法。
我建议您观看 Firebase video series 中关于“JavaScript Promises”的 3 个官方视频,然后您首先尝试使用 then()
方法正确 chain你的 promise 并返回链。
下面的代码应该可以工作。
exports.fcmTester = functions.firestore.document('posts/{postID}').onCreate((snapshot, context) => {
const notificationMessageData = snapshot.data();
return admin.firestore().collection('pushTokens').get()
.then(snapshot => {
var tokens = [];
if (snapshot.empty) {
console.log('No Devices');
throw new Error('No Devices');
} else {
for (var token of snapshot.docs) {
tokens.push(token.data().tokenID);
}
var payload = {
"notification": {
"title": "from" + notificationMessageData.writer,
"body": "from" + notificationMessageData.name,
"sound": "default"
},
"data": {
"sendername": notificationMessageData.writer,
"message": notificationMessageData.name
}
}
return admin.messaging().sendToDevice(tokens, payload)
}
})
.catch((err) => {
console.log(err);
return null;
})
});
<小时/>
那么,在体验了then()
(和catch()
)对异步方法的“管理”之后,你可以尝试一下async/await
:同样,这个official video道格·史蒂文森的帮助将会很大。
关于node.js - 如何使用nodejs发送firebase通知?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59089836/