如何以及何时与谷歌的云功能的承诺正常返回值?
我慢慢地Node.js的工作我的方式我有一个基本的iOS应用(SWIFT),他们推送消息到公司的FireStore和我使用的节点时更新数据库发送通知。
exports.updateRequestToJoin = functions.firestore
.document('/chats/{chatId}')
.onUpdate(event => {
if(userId != sentBy)
{
return db.collection('users').doc(userId).get().then(doc => {
var payload = {
notification:{
title: "msg",
body: "send msg"
}
};
admin.messaging().sendToDevice(fcm_token, payload)
.then(function(response) {
// See the MessagingDevicesResponse reference documentation for
// the contents of response.
console.log("Successfully sent message:", response);
})
.catch(function(error) {
console.log("Error sending message:", error);
});
};
return 0
});
起初,我只是有return
在功能的目的,而是得到错误“功能返回undefined,预期承诺或价值”,直到我用return 0
而且似乎沉默的错误。
我很确定的事情是:
- 正在恢复像0 OK实践价值?
- 当错误说“无极预期或价值”并承诺指的是
.then
? - 在if语句,我回到了db.collection - 是要返回或者我可以跳过
return
关键字?
谢谢。
回答如下:在这里你有很好的问题。开始的地方是函数调用程序。要导出updateRequestToJoin()。什么是主叫方期待?你在成功或失败代码退出函数的角度思考?节点的应用程序往往比脚本只返回布尔值不同的环境中工作。整个节点的风气是关于支持单线程环境,是幸福的异步执行。因此,节点功能往往要么返回承诺,与他们的内置解决或拒绝的方法;或者它们运行的回调。
如果你想仅仅停留在你的catch语句返回你再陈述一个成功代码或失败代码,你可以的东西这样简单:
if(userId != sentBy)
{
db.collection('users').doc(userId).get().then(doc => {
var payload = {
notification:{
title: "msg",
body: "send msg"
}
};
admin.messaging().sendToDevice(fcm_token, payload)
.then(function(response) {
// See the MessagingDevicesResponse reference documentation for
// the contents of response.
console.log("Successfully sent message:", response);
return true;
})
.catch(function(error) {
console.log("Error sending message:", error);
return false;
});
};
成败在随后/赶上你admin.messaging链的返回。
这就是那种回答你的第一个问题和部分回答你的第二个。更完整的回答你的第二个问题,需要一点点的阅读。 Promise是土生土长的Javascript对象,让你方便的方法来处理异步执行。您呼叫的db.collection链和admin.messaging链是在当时的返回下决心的承诺(或某种thenable构建的),并在catch拒绝(不使用的渔获侧db.collection电话,但您使用的是admin.messaging呼叫的捕获侧)。
最后,至于是否需要返回db.collection链,你可以这样做,如果db.collection电话是函数调用数组的Promise.all执行的一部分。在这种情况下,然而,它看起来像你想简单地返回一个成功或失败的代码,根据您的通话admin.messaging的成功或失败。
我想提出一些假设你的目标在这里。我们希望,至少,这移向清晰的讨论。