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

Firebase云功能-快照.forEach(…)。则不是函数

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

    我的数据库布局是:

    @posts
       @postId_abc
         -total_score: ... // will update from cloud function
         -score_count: ... // will update from cloud function
    
    @scores
       @postId_abc
          -uid_1: 10
          -uid_2: 20
          _uid_3: 50
    

    cloud function 把所有的分数加起来 分数 参考并将其设置为 total_score 那个岗位上的财产。当我尝试下面的代码时,会出现错误:

    FIREBASE WARNING: Exception was thrown by user callback. TypeError: snapshot.forEach(...).then is not a functio Exception from a finished function: TypeError: snapshot.forEach(...).then is not a function

    看来我的 snapshot.forEach((child) => { ... }).then(() => { scoreCountProperty.set(...)

    const functions = require('firebase-functions');
    const admin = require('firebase-admin');
    admin.initializeApp();
    
    exports.updateScore = functions.https.onCall((data, response) => {
    
        const postId = data.postId;
    
        const postsRef = admin.database().ref('/posts/' + postId);
        const scoreCountProperty = admin.database().ref('/posts/' + postId + '/' + 'score_count');
    
        var totalScore = 0.0;
    
        admin.database().ref('scores').child(postId).once('value', snapshot => {
    
        if (snapshot.exists()) {
    
            snapshot.forEach((child) => {
    
                totalScore += child.val()
    
            })
            .then(() => { 
                    
                console.log('totalScore: ', totalScore);
    
                return postsRef.set({ "total_score": totalScore });       
            })
            .then(() => { 
                    
                return scoreCountProperty.set(admin.database.ServerValue.increment(1));                
            })
            .catch((error) => {
                console.log('ERROR - updateScore Failed: ', error);
            });
        });
    });
    
    2 回复  |  直到 3 年前
        1
  •  0
  •   Frank van Puffelen    3 年前

    正如错误信息所说, Snapshot.forEach() 不返回可以调用的对象 then()

    但你不需要 不管怎样,自从 快照.forEach()

    所以这应该是你想要的:

    snapshot.forEach((child) => {
        totalScore += child.val()
    })
    console.log('totalScore: ', totalScore);
    
    return postsRef.set({ "total_score": totalScore }).then(() => { 
        return scoreCountProperty.set(admin.database.ServerValue.increment(1));                
    })
    .catch((error) => {
        console.log('ERROR - updateScore Failed: ', error);
    });