【问题标题】:Retrieving a few random snapshots from the same giant Firebase DB object从同一个巨型 Firebase DB 对象中检索一些随机快照
【发布时间】:2016-12-28 08:59:08
【问题描述】:

如何从 NodeJS 中的对象中获取随机隔离值?我如何知道请求是否以及何时得到满足?我的意思是不这样做:

http.createServer(function(request, response) {
    var obj = [];
    ref("games").child(rnd(range)).once("value").then(function(snapshot) {
        obj.push(snapshot.val());
    }).then(function() {
        ref("games").child(rnd(range)).once("value").then(function(snapshot) {
            obj.push(snapshot.val());
        }).then(function() {
            ref("games").child(rnd(range)).once("value").then(function(snapshot) {
                obj.push(snapshot.val());
            }).then(function() {
                ref("games").child(rnd(range)).once("value").then(function(snapshot) {
                    obj.push(snapshot.val());
                }).then(function() {
                    ref("games").child(rnd(range)).once("value").then(function(snapshot) {
                        obj.push(snapshot.val());
                    }).then(function() {
                        ref("games").child(rnd(range)).once("value").then(function(snapshot) {
                            obj.push(snapshot.val());
                        }).then(function() {
                            response.end(JSON.stringify(obj));
                        });
                    });
                });
            });
        });
    });
}).listen(8081);

我似乎无法运行递归代码,因为我是新手,而且有太多数据在移动。

【问题讨论】:

  • rnd(range) 返回一些随机键,而您尝试连续获取多个值?
  • @qxz 返回Math.floor(Math.random() * range)。没什么特别的。

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


【解决方案1】:

按顺序执行每个请求可能不是最好的方法;没有理由在启动下一个之前等待最后一个完成。当然,诀窍是知道最后一个请求何时完成。我通常只使用一个计数器:

function getSomeStuff(numToGet, callback) {
  var obj = []; // accumulates the results
  var numDone = 0; // keeps track of how many of the requests have completed
  for (var n=0; n<numToGet; n++) {
    ref("games").child(rnd(range)).once("value", function(snapshot) {
      // NOTE: inside this function, n will always ==numToGet!
      obj.push(snapshot.val());
      if (++numDone == numToGet) { // if this is the last request to complete,
        callback(obj); // call the callback with the results
      }
    });
  }
}

然后在您的 http 处理程序中,简单地说:

getSomeStuff(6, function(obj) {
  response.end(JSON.stringify(obj));
});

【讨论】:

  • 我知道顺序请求很糟糕,但我只是想说明我想要完成的事情。您的代码运行良好!它也非常快,太棒了。
猜你喜欢
  • 2013-09-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-15
  • 1970-01-01
相关资源
最近更新 更多