如何使For循环等待Firebase数据库响应?

时间:2017-02-20 11:31:24

标签: javascript arrays firebase firebase-realtime-database

我有一个接收对象数组的函数。该数组如下所示:

var receivedObjects = [{nuih329hs: 100}, {8suwhd73h: 500}, {2dsd73ud: 50}, {9u238ds: 200}];

每个键都是一个ID,每个值都是一个数字。 对象按设定顺序排列,我想要做的是遍历对象并将每个值定义为变量,然后在创建html行时使用。

我遇到的问题是,我必须在此迭代代码中调用Firebase数据库,结果是在为每个对象值成功创建一行时,输入每行的值始终为相同(对象数组中的最后/最近的值),因此在上面的情况下,数字200出现在所有四行中。

我认为这可能会发生,因为可能所有迭代都在第一个Firebase调用完成之前完成,这意味着变量currentValue(我正在进入行中)被设置为最后一个值在第一次Firebase调用之前的数组。

注意:还有另一个包含Firebase ID的阵列(名为listOfIds),我能够成功地将此阵列中的每个ID用作Firebase调用中使用的变量,var currentID是那个变量。

这是功能:

function populateTable(receivedObjects){

   var receivedObjectsLength = receivedObjects.length;
   // Note: an object array called listOfIds exists here (containing Firebase IDs to be used for querying Firebase), it's referenced below.

   for (var i = 0; i < receivedObjectsLength; i++) {

      // listOfIds is an Object array 
      var currentID = Object.keys(listOfIds[i]);

      var term = (Object.keys(receivedObjects[i])[0]);
      var currentValue = receivedObjects[i][term];

      //The following line is showing the correct ID and Value for each iteration:
      console.log("The current ID is: "+currentID+" and the current value is: "+currentValue);

      firebase.database().ref('/users/' + currentID).once('value').then(function(child) {

      // This is where the rows are created, ``currentValue`` is used here, but it's appearing as the same value in every row.

      // The next line is showing the correct current ID, but it's showing the currentValue as "200" in every row.
      console.log("The current ID is: "+currentID+" and the current value is: "+currentValue);

    });
  }
}

我很困惑,因为我认为Javascript迭代代码会等到从Firebase调用返回数据,但似乎情况并非如此?如何更改我的代码,以便Firebase调用成功函数中的行console.log("The current ID is: "+currentID+" and the current value is: "+currentValue);将显示正确的currentValue

1 个答案:

答案 0 :(得分:4)

您可以使用函数将SELECT [LRSNum],[AppUpdD],[AppStat],[PIN] FROM OPENROWSET('MICROSOFT.ACE.OLEDB.12.0','dBASE 5.0;Database=D:\Sales- data\SalesSourcefile\2016\December\Shape\Martin\real_land\', 'SELECT [LRSNum],[AppUpdD],[AppStat],[PIN] FROM real_land.dbf'); currentID放入自己的范围,而不是让循环等待,这样它们就不会被每次迭代覆盖:

currentValue

在你的循环中:

function getUser(currentID, currentValue) {
    return firebase.database().ref('/users/' + currentID).once('value').then(function(child) {
        console.log("The current ID is: "+currentID+" and the current value is: "+currentValue);
    });
}
相关问题