I’m looping over an array of JSON data returned from couchdb, and added the data to an array then returning the array, The array should contain the rows from couchdb but [] is returned.
var Album = {
all: function() {
var data, albums = [];
request({ uri: 'http://127.0.0.1:5984/albums/_all_docs'}, function(error, response, body) {
if (error) throw error;
data = JSON.parse(body);
data.rows.forEach(function(d) {
request({ uri: 'http://127.0.0.1:5984/albums/' + d.id }, function(error, response, body) {
if (error) throw error;
albums.push(JSON.parse(body));
});
});
});
return albums;
}
};
[]will be returned initially, although once the callback executes the array will contain the necessary data. That’s the nature of node’s callbacks – they are asynchronous.