【问题标题】:Firebase Cloud Functions - snapshot.forEach(...).then is not a functionFirebase 云函数 - snapshot.forEach(...).then 不是函数
【发布时间】:2021-02-15 03:30:31
【问题描述】:

我的数据库布局是:

@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 functionscores 参考中的所有分数相加,并将它们设置为该特定帖子的 total_score 属性。当我尝试下面的代码时,我得到了错误:

FIREBASE WARNING: Exception was thrown by user callback. TypeError: snapshot.forEach(...).then is not a functioException 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);
        });
    });
});

【问题讨论】:

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


    【解决方案1】:

    正如错误消息所述,Snapshot.forEach() 不会返回您可以调用 then() 的对象。事实上,我很确定它什么也没有返回。

    但无论如何您都不需要then(),因为Snapshot.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);
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-10-07
      • 2020-03-14
      • 2020-11-05
      • 2020-06-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多