开发者

empty array when nesting callbacks

开发者 https://www.devze.com 2023-02-25 03:49 出处:网络
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.

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(JS开发者_如何学GoON.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.


To add to what davin said, you normally handle asynchronous operations with callbacks. The problem with your code is that if you have n different albums, you have n different request operations happening simultaneously but you have no way of knowing when they all finish.

I'm not a Node.js guy, so maybe there are utilities to handle this, but with vanilla javascript, here's how I would handle such a thing with minimal changes to your code.

Here's some pseudo-javascript for brevity

Album.all = function(callback){
    request( "_all_docs", function(albums){
        var albumsLeft = albums.length;
        var results = [];
        albums.forEach( function(album_id){
            request( "albums/" + album_id, function(album){
                results.push(album);
                albumsLeft -= 1;                
                if( albumsLeft === 0){
                    callback(results);
                }
            });
        });
    });
};
0

精彩评论

暂无评论...
验证码 换一张
取 消