Emi*_*ily 1 javascript arrays firebase firebase-realtime-database
我有一个接收对象数组的函数。该数组如下所示:
var receivedObjects = [{nuih329hs: 100}, {8suwhd73h: 500}, {2dsd73ud: 50}, {9u238ds: 200}];
Run Code Online (Sandbox Code Playgroud)
每个键都是一个 ID,每个值都是一个数字。对象按固定顺序排列,我想要做的是遍历对象并将每个值定义为一个变量,然后我将在创建 html 行时使用该变量。
我遇到的问题是,我必须在此迭代代码中调用 Firebase 数据库,结果是,虽然为每个对象值成功创建了一行,但输入到每一行中的值始终相同(对象数组中的最后一个/最近的值),因此在上述情况下,数字200出现在所有四行中。
我认为这可能会发生,因为可能所有迭代都在第一个 Firebase 调用完成之前完成,这意味着变量currentValue(我正在输入到行中)在第一个 Firebase 调用之前设置为数组中的最后一个值制作。
注意:还有另一个listOfIds包含 Firebase ID 的数组(称为),我能够成功地使用该数组中的每个 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);
});
}
}
Run Code Online (Sandbox Code Playgroud)
我很困惑,因为我认为 Javascript 迭代代码会等到数据从 Firebase 调用返回,但似乎并非如此?如何更改我的代码,以便console.log("The current ID is: "+currentID+" and the current value is: "+currentValue);Firebase 调用成功函数中的行显示正确currentValue?
而不是使循环等待,你可以使用函数把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);
});
}
Run Code Online (Sandbox Code Playgroud)
在你的循环中:
for (var i = 0; i < receivedObjectsLength; i++) {
...
getUser(currentID, currentValue)
}
Run Code Online (Sandbox Code Playgroud)