user2071586
user2071586

Reputation: 13

Put some documents from CouchDB to Array (Node.JS)

I try get 3 documents with IDs: 1, 100, 1000. But node.js is async, and array objects in result is empty. How put documents into array?

var objects = {};
var objectsID = [1, 100, 1000];
objectsID.forEach( function( elem ){
  objectsDB.get( elem, function( err, object ){
    objects[elem] = object;
   })
 });
 console.log(objects);

console.log returns {}.

Upvotes: 1

Views: 125

Answers (1)

freakish
freakish

Reputation: 56587

So this is a classical asynchronous code issue. Your code can be rewritten like this:

var objects = {};
var objectsID = [1, 100, 1000];

var finalize = function( ) {
    console.log(objects);
};

objectsID.forEach( function( elem ){
    objectsDB.get( elem, function( err, object ){
        objects[elem] = object;

        // remove ID from the list of IDs
        var idx = objectsID.indexOf(elem);
        if (idx!=-1) {
            objectsID.splice(idx, 1);
        }

        // check if it is time to finalize
        if (!objectsID.length) {
            finalize();
        }
    })
});

You might want to have a look at Caolan's async.js library as well ( in particular async.parallel ).

Upvotes: 2

Related Questions