views:

79

answers:

1

I have written the following code using node.js and riak-js. I have a recursive function walk that should be a list of JSON documents, but instead returns an empty list... why? how to fix?

require('riak-js');

var walk = function(bucket, key, list){ 
  if(list == undefined){
    var list = new Array();
  } 
  db.get(bucket, key)(function(doc, meta){     
     list.push(doc);
     if(meta.links.length > 0 && meta.links[0].tag == 'child'){
       walk(bucket, meta.links[0].key, list);
     }   
  });
  return list; 
}

familytree = walk('smith', 'walter', []);  

Thanks in advance!

+4  A: 

You get an empty array because db.get() is asynchronous. It returns immediately without waiting for the callback to be invoked. Therefore when the interpretor reaches the return list statement, list is still an empty array.

It is a fundamental concept in Node.js (and even in browser scripting) that everything is asynchronous (non-blocking).

Daniel Vassallo