首页 文章

Firebase Cloud 功能错误:函数返回undefined,预期Promise或value

提问于
浏览
0

除了日志总是显示错误之外,我完全想要算法的算法: Function returned undefined, expected Promise or value . 我发现错误消失了 . 代码的重要片段如下 .

我已经正确地回复了一个承诺 . 任何想法如何使错误消失?

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

2 回答

  • 1

    您将返回以返回sendNotificationMessage返回的promise . 这就是Cloud Functions在完成所有异步工作时所知道的:

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

    Firebase的 Cloud 功能由后台 must return a 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 . 因此,您应该在 Cloud 函数中链接这些承诺 . 这可能应该按如下方式完成,但如果没有完整的代码,很难保证这是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团队的这两个视频,它们解释了为什么以及如何回复承诺:

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

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

    第一个更多是关于通过HTTP请求触发的HTTP函数(因此不是背景事件),而第二个是关注背景事件触发函数,但建议在观看第二个之前观察第一个 .

相关问题