2016-08-21 45 views
0

如何从NodeJS中的某个对象获取随机隔离值?我如何知道请求是否以及何时被满足?我的意思是没有这样做:从同一个巨型Firebase DB对象中检索几个随机快照

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); 

我似乎无法得到递归代码去,因为我是新来的这一点,有这么多的数据走动。

+0

'RND(范围)'返回一些随机密钥,和你想得连续几个值? – qxz

+0

@qxz它返回'Math.floor(Math.random()* range)'。没有什么花哨。 –

回答

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)); 
}); 
+0

我知道顺序请求不好,但我只是试图说明我想要完成的事情。你的代码工作得很好!它的速度也非常快,非常棒。 –

+0

很高兴传播知识。不要忘记将答案标记为可接受;) – qxz