代码之家  ›  专栏  ›  技术社区  ›  Lance Samaria

云函数如何嵌套Promise

  •  0
  • Lance Samaria  · 技术社区  · 4 年前

    我需要做出一些承诺。

    我首先需要使用以下命令来递增ref: .set(admin.database.ServerValue.increment(1))

    一旦完成,我需要在不同的参考处更新一些数据: return admin.database().ref('/user_credits/' + creditId + '/' + userId).set({ "joined_date": receivedTimeStamp, "timeStamp": receivedTimeStamp, "credits_count": 1 })

    以下代码正常工作,两个引用都按预期更新,但我收到了以下警告:

    enter image description here

    const functions = require('firebase-functions');
    const admin = require('firebase-admin');
    admin.initializeApp();
    
    exports.updateViewsCtAtPostsRef = functions.https.onRequest((request, response) => {
    
        const currentTimeStamp = Date.now();
        const receivedTimeStamp = admin.database.ServerValue.TIMESTAMP;
    
        const creditId = "sample_123";
        const userId = "userId_xyz";
        const gameId = "game_abc";
        admin.database().ref('user_credits').child(creditId).child(userId).once('value', snapshot => {
    
            if (!snapshot.exists()) {
    
                admin.database().ref('/games/' + gameId + '/' + 'score').set(admin.database.ServerValue.increment(1))
                .then(() => { 
    
                    return admin.database().ref('/user_credits/' + creditId + '/' + userId).set({ "joined_date": receivedTimeStamp, "timeStamp": receivedTimeStamp, "credits_count": 1 })
                    .then(() => { 
                        return true; 
                    })
                    .catch(error);
                })
                .catch(error);
    
            } else {
    
                const previousTimeStamp = snapshot.child("timeStamp").val();
                const creditsCount = snapshot.child("credits_count").val();
    
                if (previousTimeStamp + whatever) < currentTimeStamp {
    
                    let updatedCount = creditsCount + 1;
    
                    admin.database().ref('/games/' + gameId + '/' + 'score').set(admin.database.ServerValue.increment(1))
                    .then(() => {
    
                        return admin.database().ref('/user_credits/' + creditId + '/' + userId).update({ "timeStamp": receivedTimeStamp, "credits_count": updatedCount })
                        .then(() => { 
                            return true; 
                        })
                        .catch(error);
                    })
                    .catch(error);
    
                } else {
    
                   return true
                }
            }
        });
    });
    
    0 回复  |  直到 4 年前