nodejs firebase实时数据库排序不起作用

时间:2018-04-01 09:12:32

标签: node.js firebase firebase-realtime-database

我有一些用nodejs编写的代码,它利用firebase实时数据库打印出一些数据。我希望他们按顺序打印出来,但orderByChild(" adscore2017")无效。

const ref = admin.database().ref('/programmelist');
var speech = "The scores are: ";

ref.orderByChild('adscore2017').on("value", function(snap) {
    var numOfChildren = snap.numChildren();
    for (var i = 1; i <= numOfChildren; i++) {
        var path = ref.child(i);
        path.on("value", function(snap) {
            speech += snap.val().adscore2017+", ";
        });
    }
    app.ask(speech)  //print the output
});

这是我database的结构。预期的输出应该是:

The scores are 20.8, 21,6, 21.8.....

但是当前的输出:

The scores are 21.8, 20.8, 21.6.....

显然不合适。有人请帮帮我。感谢。

1 个答案:

答案 0 :(得分:1)

我认为forEach循环检索数据后会更好,因为for方法是同步循环,但您尝试检索此循环异步内的数据。因此,以下小改动可能有效:

ref.orderByChild('adscore2017').on("value", function(snap) {
   snap.forEach((s,inx) =>{
      speech += s.val().adscore2017+", ";
   })
   if (inx==snap.numChildren()-1) {
      app.ask(speech)  //print the output
   }
});