2

I'm having a problem with a callback mess.

In my nodejs app, I'm trying to get an array of JSON Objects returned by a mongoDB request. I don't know why, but it don't populate as I want.

I suspect a problem of asynchronous results/callback mess.

var fruits = ["Peach", "Banana", "Strawberry"];
var finalTab = [];
fruits.forEach(function(fruit) {
    db.collection('mycollection').distinct("column1", {"column2":{$regex :fruit}}, (function(err, result) {                 
        finalTab[fruit] = result;
        console.log(result); // -> display the desired content
        db.close();
        if (err) throw err;
    }));
});
console.log(finalTab); // -> []

Thanks by advance for help.

EDIT : As I need all results returned by my db.collection...functions... I'm trying to add these async commands to a queue, execute it and get a callback function. I think that async nodejs module can help.

Can someone tell me how to do this in a ForEach() ?

1 Answers1

0

The line finalTab[fruit] = result; will not help because fruit there is not index. You need to use index in forEach() as follows -

var fruits = ["Peach", "Banana", "Strawberry"];
var finalTab = [];
fruits.forEach(function(fruit, index) {
    db.collection('mycollection').distinct("column1", {"column2":{$regex :fruit}}, (function(err, result) {                 
        finalTab[index] = result;
        console.log(result); // -> display the desired content
        db.close();
        if (err) throw err;
    }));
});
console.log(finalTab); // -> []
Rishikesh Dhokare
  • 3,559
  • 23
  • 34