Maxime Girou Maxime Girou - 5 months ago 61
Node.js Question

mongoose how to pass extra parameter in exec callback function

I have the following loop:

params = ['Thing', 'AnotherThing', 'AnotherThingAgain'];
for (i in params){
MyModel.find(....).exec(function(err, data){
// do some stuff here
});
}


So, when my request is executed, I want to use
params[i]
in the callback function. The problem is the request seems to be executed asynchronously so
params[i]
always take the last value of my array (
'AnotherThingAgain'
here).

How can I pass an extra parameter to that callback function in the purpose of using it in the function?

Answer

The simplest way is to use closure:

var params = ['Thing', 'AnotherThing', 'AnotherThingAgain'];

params.forEach(function(param, i){
    MyModel.find(....).exec(function(err, data){
     // do some stuff here with param or i
    });
});