0

FYI: This is pseudo code as the real code is very large.

I have a function main(). Main has a callback that should be sent an array of results found in the mongodb. As an example main will be sent an array of URLs and should send to its callback information saved in Mongo for each URL. Basically an array of objects.

My problem is that everything is asynchronous and main is calling its callback multiple times.

Does anyone have any advice on making functions synchronous?

var db = require('moongoose');
mongoose.connect(__config.db.connect);
Schema = mongoose.Schema;

var scrapeSchema = require('./scrape.schema');
var Scrape = mongoose.model('Scrape', scrapeSchema);

function findResultWithParams(findParams, select, callback) { 
    Schema.find(findParams).sort('-timestamp').select(select).exec(function (err, found) {
        if (err) return handleError(err);

        callback(err, found[0]);
    });
}

function main(array, callback) {
    var results = [];

    var addToResults = function(err, found) {
        results.push(found);
        if(results.length >= array.length) callback(err, results);
    }

   for(var i = 0; i < array.length; i++)
   {
        findResultWithParams({ _id: array[0]._id }, '', function (err, foundArray) 
        {
            if (!foundArray || foundArray.length <= 0 || isTooOld(foundArray[0].timestamp, msg.header.maxResponseAge)) {
                console.log('findResultWithParams Return false');
                callback(err, false);
            } else {
                console.log('findResultWithParams ok');
                addToResults(err, foundArray[0]);
            }
        });
    };
}
RachelD
  • 4,072
  • 9
  • 40
  • 68
  • Is your goal to invoke the callback multiple times but wait for all callback invocations to return before the main function continues? – Will Oct 01 '13 at 20:40
  • From main I only want its callback called once. Ive tried a few things but to no avail. – RachelD Oct 01 '13 at 20:41
  • Hmm, findResultWithParams itself is called several times; are you trying to get rid of the for loop? Also, is the "callback" you mention in your question the "callback" function, or the anonymous function that is passed as the 3rd argument to findResultWithParams? Caveat -- I'm unfamiliar with Mongo and this library, just familiar with JavaScript. =) – Will Oct 01 '13 at 21:02
  • I want to gather all of the results from findResultWithParams() in the results array, and to send that back to the callback that was sent as a parameter to main. Once. – RachelD Oct 01 '13 at 21:13

0 Answers0