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() ?

2

1 Answer 1

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); // -> []
Sign up to request clarification or add additional context in comments.

4 Comments

While this is a baby step in the right direction, there are still multiple problems with your code.
Is it possible to use the content of the fruit variable as a key of the array ? Like this -> [ 'Peach' => {myobject}, 'Banana' => ....etc ]
I edited my question Patrick. Can you help ?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.