javascript firebase数据库获取值分组

javascript firebase数据库获取值分组

问题描述:

我需要在连续的这些值,但我不希望他们答复,如果它已经在div。javascript firebase数据库获取值分组

我的尝试就在这里。我尝试构建一个数组并将这些值从firebase放到这里,但仍然无法在html中看到。

var fruits = []; 
    var fetchPostsleft = function(postsRef, sectionElement,fruits) { 
    postsRef .orderByChild('timeStamp').on('child_added', function(data) { 
     console.log(data.val()); 
     var author = data.val().senderName; 


     var containerElement2 = sectionElement.getElementsByClassName('posts-containerleft')[0]; 

     fruits.push(data.val().senderName); 
     console.log(fruits.length); 


    }); 

    }; 


    fetchPostsleft(topUserPostsRef, topUserPostsSectionleft,fruits); 
var fLen = fruits.length; 
     console.log(fruits.length); 

for (var i = 0; i < fLen; i++) { 
    // text += "<li>" + fruits[i] + "</li>"; 
    topUserPostsSectionleft.getElementsByClassName('posts-containerleft')[0].insertBefore(createheaders(fruits[i], ""), 
    topUserPostsSectionleft.getElementsByClassName('posts-containerleft')[0].firstChild); 
} 

数据是从Firebase异步加载的。这意味着,当你在数组上循环时,它还没有被填充。这是最简单的用几个日志报表取代了大部分的代码,看到这一点:

console.log("Before query"); 
postsRef.orderByChild('timeStamp').on('child_added', function(data) { 
    console.log("In child_added"); 
}); 
console.log("After query"); 

如果运行这个片段中,记录将是:

查询

之前

查询

在child_added

这是概率根本不是你期望的顺序,因为它与日志语句在代码中的顺序不同。这是因为数据是从Firebase异步加载的,其余代码在加载时会继续。

它看到,如果你把回调到一个单独的功能稍微容易:

function onChildAdded(data) { 
    console.log("In child_added"); 
}); 

console.log("Before query"); 
postsRef.orderByChild('timeStamp').on('child_added', onChildAdded); 
console.log("After query"); 

现在你可以更容易地看到第几行只是声明onChildAdded功能。他们还没有运行它。我们只是将该函数传递给查询,以便查询每当它获取数据时都可以调用onChildAdded

这是远程服务器网页编程中最常见的陷阱。但是由于大多数现代网络都基于这种异步API,您将不得不学习它。

我发现这些作品的一种方法是重构您的问题。您当前的代码基于“首先获取帖子,然后将其添加到HTML”。但在异步编程中,最好考虑“开始提取帖子,当我们得到它们时,将它们添加到HTML”。这转化为下面的代码:

需要新的数据
function fetchPostsleft(postsRef, sectionElement) { 
    postsRef.orderByChild('timeStamp').on('child_added', function(data) { 
    var author = data.val().senderName; 
    topUserPostsSectionleft.getElementsByClassName('posts-containerleft')[0].insertBefore(createheaders(author, ""), 
    }); 
}; 

fetchPostsleft(topUserPostsRef, topUserPostsSectionleft); 

现在所有的代码是回调,所以当快照实际可用它只能运行。