【问题标题】:How to update Firebase multiple times如何多次更新 Firebase
【发布时间】:2016-04-21 22:29:45
【问题描述】:

因此,当尝试通过一个循环检查、更新和发布数据到我的 Firebase 存储时,似乎每当我尝试使用 Firebase.update() 时,它都会与我的 for 循环混淆并重复递增或根本不增加。有什么建议吗?

我的代码:

var j = 0;
    var k = 0;
    var l = 0;
    var m = 0;
    var setDict = {};
    for(var h = 0; h < teamWinNames.length; h++)
    {
        console.log(j);
        console.log(h);
        console.log(meWinList[j]);
        var tempRef = new Firebase("https://mycounter-app.firebaseio.com/user/" + username + "/championData");
        var tempName = teamWinNames[h];
        tempRef.once("value", function (teamWinSnapshot)
        {
            var exists = teamWinSnapshot.child(meWinList[j] + '/' + tempName).exists();
            console.log(exists);
            if(exists == true)                  
            {
                console.log("Here");
                var tempVal = teamWinSnapshot.child(meWinList[j] + '/' + tempName).val();
                console.log(tempVal);
                //var tempValue = obj[tempname][tempchamp];
                //console.log(tempValue);
            }
            else
            {
                setDict[tempName] = '1-0-0-0';
                console.log(setDict);
            }

        });
        if(h != 0 && (h+1)%4 == 0)
        {
            sendUpdate(setDict, meWinList[j], username);
            setDict = {};
            j++;
        }
    }

以及进行更新的函数:

function sendUpdate(data, champ, username)
{
    var tempRef = new Firebase("https://mycounter-app.firebaseio.com/user/" + username + "/championData");
    tempRef.child(champ).update(data);
}

【问题讨论】:

    标签: javascript firebase firebase-realtime-database


    【解决方案1】:

    问题是您在 for 循环中获取数据并在循环内更改它。这意味着您在循环中使用的数据会随着每次迭代而变化。作为一个额外的好处,您可以获得 firebase 的异步特性的效果,看起来像这样:

    • 获取数据 (1)
    • 获取数据 (2)
    • 更新数据 (1)
    • 获取数据 (3)
    • 更新数据 (3)
    • 更新数据 (2)

    为了防止这一切,我建议将 for 循环放在 tempRef.once 函数中,如下所示:(伪代码)

    tempRef.once{
        Loop through data{
            Change data
        }
        Update data
    }
    

    这意味着您只需获取一次数据并更新一次。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-11-28
      • 1970-01-01
      • 2022-11-27
      • 2017-04-14
      • 2022-01-26
      • 2017-04-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多