【问题标题】:Each then() should return a value or throw error in firebase cloud function每个 then() 都应该在 firebase 云函数中返回一个值或抛出错误
【发布时间】:2020-04-09 12:19:06
【问题描述】:

我正在使用 javascript 为 firebase 编写云函数,而我部署函数时发生错误并终止部署过程。

错误:每个 then() 都应该返回一个值或抛出

如何解决此错误?

下面我附上了我的代码。

exports.sendNotificationForLikeOrFollow = functions.database.ref('/USER_MANAGEMENT/USER_ACTIVITY/{activityId}').onCreate((snap, context) => {

  var type = snap.val().ACTIVITY_TYPE;

  if (type=='Comment') {
    return; //There is a separate function for comment notification
  }

  if (type=='Like') {

    const likeUserId = snap.val().BY_USER_NODE_NAME;
    const publishedUserId = snap.val().PUBLISHED_USER_NODE_NAME;
    const puplishedContentId = snap.val().LIKE_PUBLISHED_CONTENT_NODE_NAME;
    const likedUserName = snap.val().BY_USER_NAME;
    const likedUserPhotoUrl = snap.val().BY_USER_PHOTO_URL;

    // var publishedUserRef = event.data.ref.parent.parent.child('USERS/'+publishedUserId);
    // var likedUserRef = event.data.ref.parent.parent.child('USERS/'+likeUserId);
    var publishedUserRef = db.ref("USER_MANAGEMENT/USERS/"+publishedUserId);
    var likedUserRef = db.ref("USER_MANAGEMENT/USERS/"+likeUserId);

    return Promise.all([publishedUserRef.once('value')]).then(function(snaps) {

        var data = snaps[0].val();
        const fcmToken = data.FCM_TOKEN;

          // Notification details.
          const payload = {
            notification: {
              title: '❤️ You got a new like!',
              body: likedUserName+` liked your artwork.`,
              sound: 'default',
              icon: '',
              byUserId: likeUserId,
              byUserName: likedUserName,
              type: 'Like',
              likedPuplishedContentId: puplishedContentId,
              publishedUserId: publishedUserId,
              byUserPhotoUrl: likedUserPhotoUrl,
              badge : '1'
            }
          };

          // Listing all tokens.
          const tokens = fcmToken;

          // Send notifications to all tokens.
          return admin.messaging().sendToDevice(tokens, payload).then(response => {
            // For each message check if there was an error.
            response.results.forEach((result, index) => {
              console.log('FcmToken: ', tokens);
              const error = result.error;
              if (error) {
                console.log('Error Occured:', error);
              }
            });
            console.log('User Liked');
          });
    });
  }

  if (type=='Follow') {
    const followerUserId = snap.val().BY_USER_NODE_NAME;
    const followeeUserId = snap.val().FOLLOWING_USER_NODE_NAME;
    const followerUserName = snap.val().BY_USER_NAME;
    const followerPhotoUrl = snap.val().BY_USER_PHOTO_URL;

    // var followerUserRef = event.data.ref.parent.parent.child('USERS/'+followerUserId);
    // var followeeUserRef = event.data.ref.parent.parent.child('USERS/'+followeeUserId);
    var followerUserRef = db.ref('USER_MANAGEMENT/USERS/'+followerUserId);
    var followeeUserRef = db.ref('USER_MANAGEMENT/USERS/'+followeeUserId);
    var isFollow;

    //const followeeFollowingRef = event.data.ref.parent.parent.child('FOLLOWING/'+followeeUserId+'/'+followerUserId);
    const followeeFollowingRef = db.ref('USER_MANAGEMENT/FOLLOWING/'+followeeUserId+'/'+followerUserId);

    return Promise.all([followeeUserRef.once('value')]).then(function(snaps) {

        var data = snaps[0].val(); // Get whole USER_MANAGEMENT snapshot

        const fcmToken = data.FCM_TOKEN

        followeeFollowingRef.once('value').then(function(followeeSnapshot) {

          if (followeeSnapshot.exists()) {
            isFollow = 'YES';
            console.log('FOLLOW YES');
          }else{
            isFollow = 'NO';
            console.log('FOLLOW NO');
          }

            // Notification details.
            const payload = {
              notification: {
                title: '???? You have a new follower!',
                body: followerUserName+` is now following you.`,
                sound: 'default',
                icon: '',
                byUserId: followerUserId,
                byUserName: followerUserName,
                type: 'Follow',
                isFollow: isFollow,
                byUserPhotoUrl: followerPhotoUrl,
                badge : '1'
              }
            };

            // Listing all tokens.
            const tokens = fcmToken;
            console.log('FcmToken: ', tokens);
            // Send notifications to all tokens.
            return admin.messaging().sendToDevice(tokens, payload).then(response => {
              // For each message check if there was an error.
              response.results.forEach((result, index) => {
                const error = result.error;
                if (error) {

                  console.log('Error Occured:', error);
                }
              });
              console.log('User Followed');
            });
      });    
    });
  }
});

该功能在几年前就已经部署并且运行良好。但现在我尝试将相同的代码部署到另一个项目,但由于上述错误而停止。

【问题讨论】:

    标签: javascript node.js firebase firebase-realtime-database google-cloud-functions


    【解决方案1】:

    您没有正确chain Firebase 异步方法返回的不同承诺。

    另外,请注意您不需要使用Promise.all(),因为once() 方法只返回一个Promise。同样,您应该正确链接 Promises,而不是使用Promise.all(),它应该用于并行而不是按顺序执行异步方法。

    因此,以下应该可以解决问题(未经测试):

    exports.sendNotificationForLikeOrFollow = functions.database.ref('/USER_MANAGEMENT/USER_ACTIVITY/{activityId}').onCreate((snap, context) => {
    
        var type = snap.val().ACTIVITY_TYPE;
    
        if (type == 'Comment') {
            return null; //There is a separate function for comment notification
        }
    
        if (type == 'Like') {
    
            const likeUserId = snap.val().BY_USER_NODE_NAME;
            const publishedUserId = snap.val().PUBLISHED_USER_NODE_NAME;
            const puplishedContentId = snap.val().LIKE_PUBLISHED_CONTENT_NODE_NAME;
            const likedUserName = snap.val().BY_USER_NAME;
            const likedUserPhotoUrl = snap.val().BY_USER_PHOTO_URL;
    
            var publishedUserRef = db.ref("USER_MANAGEMENT/USERS/" + publishedUserId);
    
            return publishedUserRef.once('value')
                .then(snaps => {
    
                    var data = snaps[0].val();
                    const fcmToken = data.FCM_TOKEN;
    
                    // Notification details.
                    const payload = {
                        notification: {
                            title: '❤️ You got a new like!',
                            body: likedUserName + ` liked your artwork.`,
                            sound: 'default',
                            icon: '',
                            byUserId: likeUserId,
                            byUserName: likedUserName,
                            type: 'Like',
                            likedPuplishedContentId: puplishedContentId,
                            publishedUserId: publishedUserId,
                            byUserPhotoUrl: likedUserPhotoUrl,
                            badge: '1'
                        }
                    };
    
                    // Listing all tokens.
                    const tokens = fcmToken;
    
                    // Send notifications to all tokens.
                    return admin.messaging().sendToDevice(tokens, payload);
                })
                .then(response => {
                    // For each message check if there was an error.
                    response.results.forEach((result, index) => {
                        console.log('FcmToken: ', tokens);
                        const error = result.error;
                        if (error) {
                            console.log('Error Occured:', error);
                        }
                    });
                    console.log('User Liked');
                    return null;
                });
        }
    
        if (type == 'Follow') {
            // See above, it is similar
        }
    });
    

    【讨论】:

    • Renaud Tarnec 感谢您的回答。但是我根据您的回答更改了“关注”部分,它显示了一些警告消息(警告:“避免嵌套承诺”)。你能为我编辑整个函数吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-01-22
    • 1970-01-01
    • 2019-02-19
    • 2018-09-25
    • 2020-04-02
    • 2018-09-11
    • 1970-01-01
    相关资源
    最近更新 更多