gpt4 book ai didi

javascript - Firebase云函数错误: Function returned undefined,预期的Promise或值

转载 作者:行者123 更新时间:2023-12-01 01:56:21 24 4
gpt4 key购买 nike

我定义了一个 Firebase 云函数,该函数在实时数据库 onCreate 触发器上执行。该函数完美地执行了预期的算法,只是日志始终显示错误:函数返回未定义、预期的 Promise 或值。我已经尝试了很多方法,但仍然无法消除该错误。代码的重要片段如下。

我已经正确地返回了 promise 。有什么想法可以让错误消失吗?

index.js

const sendNotificationMessageModule = require('./sendNotificationMessage');

exports.sendNotificationMessage = functions.database.ref( '/Notifications/{pushId}').onCreate((snapshot, context) => {
sendNotificationMessageModule.sendNotificationMessage(snapshot, context, db, admin);
});

sendNotificationMessage.js

代码的第一部分:

exports.sendNotificationMessage = function(snapshot, context, db, admin) {
.
.
.

代码的最后部分:

        if(...) {
.
.
.
var androidNode = {};
androidNode[constants.propertyNotificationString] = notificationNode;
message[constants.propertyAndroidString] = androidNode;

return admin.messaging().send(message)
.then((response) => {
console.log('Successfully sent message:', response);
return snapshotNotificationMessage.ref.remove();
})
.catch((error) => {
console.log('Error sending message:', error);
});
}

可以看到,消息已成功发送,但错误仍然存​​在。当然,实时数据库中的数据也成功删除了。

cloud function error

最佳答案

由后台事件触发的 Cloud Functions for Firebase 必须返回一个 promise (或者在某些情况下返回一个值,例如return false;)。

由于 admin.messaging().send() 返回一个 Promise(请参阅 doc ),因此您只需返回此 Promise,如下所示:

var androidNode = {};
androidNode[constants.propertyNotificationString] = notificationNode;
message[constants.propertyAndroidString] = androidNode;
....
return admin.messaging().send(message);
})
.catch((error) => {
console.log('Error sending message:', error);
return false;
});

但是,您还调用了 snapshotNotificationMessage.ref.remove();,它也返回一个 promise 。因此,您应该将这些 promise 链接到您的云功能中。这应该可能按如下方式完成,但如果没有完整的代码,很难保证这是 100% 正确的。如果您将整个代码添加到您的问题中,我们可能会对其进行调整。

....
var androidNode = {};
androidNode[constants.propertyNotificationString] = notificationNode;
message[constants.propertyAndroidString] = androidNode;
return snapshotNotificationMessage.ref.remove();
.then(() => {
return admin.messaging().send(message);
})
.catch((error) => {
console.log('Error sending message:', error);
return false;
});
<小时/>

此外,我建议您观看 Firebase 团队的这两个视频,其中解释了为什么以及如何返回 Promise:

https://www.youtube.com/watch?v=7IkUgCLr5oA

https://www.youtube.com/watch?v=652XeeKNHSk

第一个更多的是关于通过 HTTP 请求触发的 HTTP 函数(因此不使用后台事件),而第二个则重点关注后台事件触发的函数,但建议先观看第一个,然后再观看第二个一个。

关于javascript - Firebase云函数错误: Function returned undefined,预期的Promise或值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51009241/

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