gpt4 book ai didi

node.js - 如何以及何时使用谷歌云函数中的 promise 正确返回值?

转载 作者:行者123 更新时间:2023-11-28 06:07:12 25 4
gpt4 key购买 nike

我正在慢慢学习 Node.js。我有一个基本的 iOS 应用程序 (swift),可以将消息推送到 Firestore,我正在使用 Node 在数据库更新时发送通知。

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,但在我使用 return 0 和这似乎消除了错误。

我不确定的事情是:

  1. 返回 0 之类的值是否可行?
  2. 当错误显示“预期的 Promise 或值”时,promise 是否指的是 .then
  3. 在 if 语句中,我返回了 db.collection - 是否有必要返回它,或者我可以跳过 return 关键字吗?

谢谢。

最佳答案

你的问题很好。从函数调用者开始。您正在导出 updateRequestToJoin()。来电者期望什么?您是否正在考虑使用成功或失败代码退出函数? Node 应用程序的工作方式往往不同于仅返回 bool 值的脚本环境。整个 Node 的精神是支持一个乐于异步执行的单线程环境。因此, Node 函数倾向于使用内置的 resolve 或 reject 方法返回 Promises;或者他们运行回调。

如果你只想在你的 then 语句中返回一个成功代码,或者在你的 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 链的 then/catch 中返回。

这是您第一个问题的答案,也是您第二个问题的部分答案。对你的第二个问题的更完整的回答需要一些阅读。 Promise是一个 native Javascript 对象,它为您提供了处理异步执行的便捷方法。您正在调用的 db.collection 链和 admin.messaging 链是 Promises(或某种 thenable 构造),它们在 then 中返回一个 resolve,在 catch 中返回一个 reject(您没有使用db.collection 调用,但您使用的是 admin.messaging 调用的 catch 端。

最后,关于是否需要返回 db.collection 链,如果 db.collection 调用是函数调用数组的 Promise.all 执行的一部分,您会这样做。然而,在这种情况下,您似乎只想根据 admin.messaging 调用的成功或失败返回成功或失败代码。

我在这里对您的目标做了一些假设。希望这至少能让讨论变得清晰。

关于node.js - 如何以及何时使用谷歌云函数中的 promise 正确返回值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47860172/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com