2

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?

JohnnyHK
  • 305,182
  • 66
  • 621
  • 471
Maxime Girou
  • 1,511
  • 2
  • 16
  • 32

1 Answers1

3

The simplest way is to use closure:

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

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

Example with Promise:

// Some function to run on param
function searchParam(param) {
    return MyModel.find({
        param: {$eq: param},
    })
    .then((result) => {
        // For eaxmple combine result with param...
        return {
            peram,
            result,
        };
    });
}

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

Promise.all(params.map(searchParam))
.then((items) => {
    // items is array of param, result pairs
    items.forEach(({param, result}) => {
        console.log(param, '=>', result);
    });
});
Paul Rumkin
  • 6,737
  • 2
  • 25
  • 35
  • Hi Pasha, Thanks it works! it was just a context problem at least! – Maxime Girou Jun 17 '16 at 14:16
  • In what sense is this a closure? Anyway, this is not the "simplest" way, which would be to say `for (let i in params`. –  Jun 17 '16 at 14:24
  • 1
    @torazaburo For me this way is the simplest because it could be transformed into `Promise.all(params.map(function (param, i) { return Model.find().exec(); ...` – Paul Rumkin Jun 17 '16 at 14:32