2

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!

3
  • 3
    Based on the guide, I think your syntax is off. It should be db.get(bucket, key, function(doc, meta)... Commented Oct 1, 2010 at 4:43
  • @Matthew Flaschen is right. Your syntax for db.get is wrong. Commented Oct 1, 2010 at 6:09
  • actually my syntax is correct for the version of riak-js I'm using (v0.2.2) - if you look at the guide, you'll see that it says "Note: This guide is only applicable to riak-js 0.3.0" Commented Oct 1, 2010 at 12:51

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.