title: returning JSON Array in Node
body: <p>Im still trying to get my head around the asynchronous flow in Node. Im trying to read list of files in db and convert result to json array and return back. The code works fine for one json object. But there is no output when reading the complete array</p>
  
  <p>So this is the code</p>
  
  <p>Function call - receive ajax request from browser and send back result</p>
  
  <pre><code>module.retrieveSourceContent(req, res, result, function(err, result){
                  if(err){
                    console.log(err);
                    return;
                  }
                  console.log(result);
                  res.contentType('json');
                  res.write(JSON.stringify(result));
                  res.end();
              });
  </code></pre>
  
  <p>Code </p>
  
  <pre><code> retrieveSourceContent : function(req, res, sourceList, callback){
          var sourceContent = new Array();
          MongoClient.connect(config.mongoPath+config.dbName, function(err, db) {
             if(err){
               return callback(new Error("Unable to Connect to DB"));
             }
             var collection = db.collection(config.source);
             for( i=0;i&lt;sourceList['sources_FOR'].length;i++){
                //build the source JSON Array
                collection.find({'_id':sourceList['sources_FOR'][i]}).nextObject(function(err, doc) {
                  if(err)
                    return callback(new Error("Error finding data in DB"));
                      var sourceObject = {
                          title     :doc.name,
                          tagCount  :doc.tag.length,
                          tags      :doc.tag,       
                          format    :doc.type,     // Differentiate text, image, video and urls
                          content   :doc.data      // Content
                      };
                      sourceContent.push(sourceObject);
                      //if(i == sourceList['sources_FOR'].length - 1)
                        return callback(null, sourceContent);
  
                });
             }
          });
        }
  </code></pre>
  
  <p>This code return one json object to client. If i uncomment <code>if(i == sourceList['sources_FOR'].length - 1)</code> i have no output and no error. But <code>sourceContent.push(sourceObject);</code> does create the json array successfully. </p>
  
  <p>Since this flow works on other language, i suspect it has something to do with asyn flow of node. Im at a loss here on how to solve this. </p>
  
  <p>Any help would be great.. </p>