I get some data from a Memcached, but the asynchrony of nodejs completely eludes me.
I want to put all the results into an object.
This is what I would do normally:
for( x = startX; x <= endX; x++ )
{
for( y = startY; y <= endY; y++ )
{
oData[ x + '_' + y ] = Db.get( x + '_' + y );
}
}
But I can’t figure out how
The Db.get() function wants a key and a callback (function(error, result) {})
This would just increment the x…
var onGet = function (error, result)
{
x++;
if(!error && result !== null)
{
oData[ x + '_' + y ] = result
}
};
Db.get(x + '_' + y, onGet);
This is not a recursion problem, it’s an “async problem.” Your issue is that NodeJS access memcached asynchronously and your procedural style code does not. So, you need to think about the problem differently.
That will work, but – you have another problem then. You have no way of knowing when your MemcacheD data has been loaded into
oData, you just have to sit and wait and guess. There are ways to deal with this; but my favorite way is to use a library namedasync.With async, you could do this:
What this code is actually doing is creating an array of functions, each of which calls the
Db.getmethod for a specific key, and adds the result to theoDatavariable.After the array of functions is created, we use the
asynclibrary’sparallelmethod, which takes an array of functions and calls them all in parallel. This means that your code will send a bunch of requests off to memcached to get your data, all at once. When each function is done, it calls thecallbackfunction, which tells theasynclib that the request finished. When all of them are finished,asynccalls the callback closure you supplied as the 2nd argument in the call to theparallelmethod. When that method is called, you either know A. something went wrong, and you have the error to recover from it or B. all requests are finished, and you may or may not have all the data you requested (expired or stale keys requested, or whatever). From there, you can do whatever you want, knowing you have finished asking for all the keys you needed.I hope this helps.