Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/41.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 每个then()都应该在firebase cloud函数中返回一个值或抛出错误_Javascript_Node.js_Firebase_Firebase Realtime Database_Google Cloud Functions - Fatal编程技术网

Javascript 每个then()都应该在firebase cloud函数中返回一个值或抛出错误

Javascript 每个then()都应该在firebase cloud函数中返回一个值或抛出错误,javascript,node.js,firebase,firebase-realtime-database,google-cloud-functions,Javascript,Node.js,Firebase,Firebase Realtime Database,Google Cloud Functions,我正在使用javascript为firebase编写一个云函数,同时部署一个发生错误的函数并终止部署过程 错误:每个then()应返回一个值或抛出 如何解决此错误 下面我附上了我的代码 exports.sendNotificationForLikeOrFollow = functions.database.ref('/USER_MANAGEMENT/USER_ACTIVITY/{activityId}').onCreate((snap, context) => { var type

我正在使用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 don't correctly chain the different promises returned by the Firebase asynchronous methods. 

Also, note that you do not need to use
Promise.all()
since the
once()
method returns only one Promise. Again, you should correctly chain the Promises, instead of using
Promise.all()
, which should be use for executing asynchronous methods in parallel, and not in sequence.

So, the following should do the trick (untested):

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
    }
});
exports.sendNotificationForLikeOrFollow=functions.database.ref('/USER\u MANAGEMENT/USER\u ACTIVITY/{activityId}')。onCreate((快照,上下文)=>{
var type=snap.val().ACTIVITY_type;
如果(类型=='Comment'){
return;//注释通知有一个单独的函数
}
如果(类型=='Like'){
const likeUserId=snap.val()。按用户节点名称;
const publishedUserId=snap.val().PUBLISHED_USER_NODE_NAME;
const puplishedContentId=snap.val()。类似于发布的内容节点名称;
const likedUserName=snap.val()。由用户名称命名;
const likedUserPhotoUrl=snap.val()。由用户图片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(“用户管理/USERS/”+publishedUserId);
var likedUserRef=db.ref(“用户管理/USERS/”+likeUserId);
返回Promise.all([publishedUserRef.one('value')))。然后(函数(快照){
var data=snaps[0].val();
const fcmToken=data.FCM_令牌;
//通知详情。
常数有效载荷={
通知:{
标题:'❤️ 你有了一个新的想法,
body:likedUserName+`喜欢你的作品。`,
声音:'默认',
图标:“”,
byUserId:likeUserId,
byUserName:likedUserName,
键入:“Like”,
likedPuplishedContentId:puplishedContentId,
publishedUserId:publishedUserId,
byUserPhotoUrl:likedUserPhotoUrl,
徽章:“1”
}
};
//列出所有令牌。
常量标记=fcmToken;
//向所有令牌发送通知。
返回admin.messaging(){
//对于每条消息,检查是否有错误。
response.results.forEach((结果,索引)=>{
log('FcmToken:',令牌);
常量错误=result.error;
如果(错误){
console.log('发生错误:',错误);
}
});
log(“用户喜欢”);
});
});
}
如果(类型=='Follow'){
const followerUserId=snap.val()。按用户节点名称;
const followeUserId=snap.val()。在用户节点名称之后;
const followerUserName=snap.val()。按用户名;
const followerPhotoUrl=snap.val()。由用户\u PHOTO\u URL创建;
//var followerUserRef=event.data.ref.parent.parent.child('USERS/'+followerUserId);
//var followeUserRef=event.data.ref.parent.parent.child('USERS/'+followeUserId);
var followerserref=db.ref('USER_MANAGEMENT/USERS/'+followerserid);
var followeueserref=db.ref('USER_MANAGEMENT/USERS/'+followeueserid);
var是跟随的;
//const followefollowingfref=event.data.ref.parent.parent.child('follower/'+followeUserId+'/'+followerUserId);
const followefollowingfref=db.ref('USER_MANAGEMENT/FOLLOWING/'+followeueserid+'/'+followeurserid');
返回Promise.all([followeUserRef.one('value')))。然后(函数(快照){
var data=snaps[0].val();//获取整个用户管理快照
const fcmToken=data.FCM_令牌
followeFollowingRef.one('value')。然后(函数(followesNapshot){
if(followesNapshot.exists()){
isFollow='是';
console.log('FOLLOW YES');
}否则{
isFollow='NO';
console.log('FOLLOW NO');
}
//通知详情。
常数有效载荷={
通知:{
title:“您没有正确选择Firebase异步方法返回的不同承诺

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

因此,以下几点应该可以做到(未经测试):


Renaud Tarnec感谢您的回答。但是我根据您的回答更改了“跟随”部分,它显示了一些警告信息(警告:“避免嵌套承诺”)。您能为我编辑整个函数吗?