如何使用javascript对firebase getDownloadURL()结果进行排序?

时间:2017-07-28 10:32:11

标签: javascript firebase firebase-realtime-database firebase-storage

此功能显示来自firebase网址的图片:

function updateTimeline(){
    var ul = document.querySelector("#timeline ul");
    ul.innerHTML = "";
    var db = firebase.database().ref("phoodos/");
    var list = db.orderByChild("timeStamp");
    list.on("child_added", function(child) {
        var selfie = child.val();

        // Retrieve the image file
        var storageRef = firebase.storage().ref();
        var imageRef = storageRef.child(selfie.path);

        imageRef.getDownloadURL().then(function(url){
            var li = "<li><figure>";
            li += "<img src='" + url + "' width='100%' alt='Phoodo'>";
            li += "<figcaption>By " + selfie.user + ": " + selfie.timeStamp + "</figcaption>";
            li += "</figure></li>";
            ul.innerHTML += li;
        })
    });
}

orderByChild的结果已排序,但getDownloadURL()的结果未排序。

如何在添加到我的html之前对getDownloadURL()检索到的图像进行排序?

1 个答案:

答案 0 :(得分:1)

一个技巧是以正确的顺序插入HTML:

var ul = document.querySelector("#timeline ul");
ul.innerHTML = "";
var db = firebase.database().ref("phoodos/");
var list = db.orderByChild("timeStamp");
list.on("child_added", function(child) {
    var selfie = child.val();

    // Retrieve the image file
    var storageRef = firebase.storage().ref();
    var imageRef = storageRef.child(selfie.path);

    var li = document.createElement("li");
    ul.appendChild(li); // this ensures the <li> is in the right order

    imageRef.getDownloadURL().then(function(url){
        var html = "<figure>";
        html += "<img src='" + url + "' width='100%' alt='Phoodo'>";
        html += "<figcaption>By " + selfie.user + ": " + selfie.timeStamp + "</figcaption>";
        html += "</figure>";
        li.innerHTML = html;
    })
});