为什么我的Firebase查询返回错误的订单?

时间:2015-11-03 10:59:36

标签: firebase

背景

大家好,我在Firebase中执行查询,检索邮件列表:

ref.child("messages").on("child_added", function(snapshot) {
    console.log(snapshot.val());
});

以上查询工作正常。它按顺序显示消息。

消息包含以下属性/字段:

<message-id>: { 
    user-id: <user-id>,
    message: "This is a sample message",
    time: 1446534920014
}   

问题

显示信息时,我还需要显示用户名。所以我需要添加另一个使用user-id字段检索用户名称的查询:

ref.child("messages").on("child_added", function(snapshot) {
    var message = snapshot.val();

    // get the user's name
    ref.child("users").child(message["user-id"]).once("value", function(userSnapshot) {
        // logs the results in the wrong order
        console.log(message, userSnapshot.val().name);
    }
});

问题是内部查询以错误的顺序返回消息列表。为什么?那么以正确的顺序显示消息的正确方法应该是什么?

修改

好的,你去吧。以下是导出的JSON:

{
  "messages" : {
    "-K2FyInlsZqLdHou1QnA" : {
      "message" : "Message 1",
      "user-id" : "-K2Fxr1gdxynukjDzcIq"
    },
    "-K2FyOlw13MU9KHB5NQh" : {
      "message" : "Message 2",
      "user-id" : "-K2Fxr1gdxynukjDzcIq"
    },
    "-K2Fz2GxPgqGf8uDfK0d" : {
      "message" : "Message 3",
      "user-id" : "-K2Fy3uyw-RNcePo_Pn-"
    }
  },
  "users" : {
    "-K2Fxr1gdxynukjDzcIq" : {
      "name" : "John Joe"
    },
    "-K2Fy3uyw-RNcePo_Pn-" : {
      "name" : "Alfred"
    }
  }
}

我的目标只是显示消息(按顺序)以及用户名。如果我这样做:

ref.child("messages").on("child_added", function(snapshot) {
    console.log(snapshot.val());
});

按顺序显示消息,即消息1,消息2,消息3.但是我仍然没有用户名,因此我需要在显示消息之前查看用户列表以检索用户名:< / p>

ref.child("messages").on("child_added", function(snapshot) {
    ref.child("users").child(snapshot.val()["user-id"]).once("value", function(userSnapshot) {
        console.log(snapshot.val(), userSnapshot.val().name);
    });
});

返回包含用户名称的消息列表,但问题是它的顺序错误:消息2,消息1,消息3

1 个答案:

答案 0 :(得分:2)

按照您期望的顺序检索邮件。您可以通过添加一些额外的日志记录来轻松验证这一点:

ref.child("messages").on("child_added", function(snapshot) {
    var message = snapshot.val();
    console.log(message.message);

    ref.child("users").child(message["user-id"]).once("value", function(userSnapshot) {
        console.log(message.message+': '+userSnapshot.val().name);
    });
});

我最近的跑步中的输出是:

"Message 1"
"Message 2"
"Message 3"
"Message 2: John Joe"
"Message 1: John Joe"
"Message 3: Alfred"

您在前三行中看到的是消息是有序的。但是,然后您开始为每个消息检索用户;并且那些用户不一定按照你解雇/期望的顺序回来。

在网络上使用AJAX时这是一个非常常见的问题:只要涉及网络流量,代码的顺序就不一定是事情发生的顺序。

解决方案始终相同:不依赖于您按特定顺序执行的代码。例如:您最有可能希望在DOM的某个列表中显示消息。

var ul = document.getElementById('messages');
ref.child("messages").on("child_added", function(snapshot) {
    var message = snapshot.val();
    var li = document.createElement('li');
    li.id = 'msg_'+snapshot.key();
    li.innerText = message.message;
    ul.appendChild(li);

    ref.child("users").child(message["user-id"]).once("value", function(userSnapshot) {
        li.innerText = userSnapshot.val().name + ': '+ li.innerText;
    });
});    

附注:您可能需要考虑添加用户名缓存。您现在将为每个用户呼叫每个消息的数据库。这是一个O(n ^ 2)操作,因此不能很好地扩展用户数。

Repro:http://jsbin.com/zofasi/edit?js,console