roder
roder

Reputation: 566

What is the scope of javascript callback and anonymous functions?

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!

Upvotes: 2

Views: 380

Answers (1)

Daniel Vassallo
Daniel Vassallo

Reputation: 344561

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

Upvotes: 3

Related Questions