【发布时间】:2017-02-20 11:31:24
【问题描述】:
我有一个接收对象数组的函数。数组如下所示:
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?
【问题讨论】:
-
另一个从函数中返回 promise 的例子,请看我刚刚写在这里的答案:stackoverflow.com/questions/42346560/…。
-
谢谢@FrankvanPuffelen,这看起来很有趣,这两种方法之间是否存在性能差异,或者它们都差不多?
-
性能的主导因素将是您读/写的数据量。如果它们之间相同,那么任何其他差异都可能无关紧要。
标签: javascript arrays firebase firebase-realtime-database