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]);
}
});
};
}