0

I have this function in nodeJS:

router.post('/listedecourses', function (req,res,next){
  var listedecourses = req.body;
  var result = [];
        for (var i=0; i<listedecourses.length; i++){
            var tata = listedecourses[i].nbpers;
        Recette.find({_id:listedecourses[i].idrecette}, function (err, docs,i) { 
            var ingredients = docs[0].ingredients;

                for (var j=0; j<ingredients.length; j++){ 
                Ingredient.find({_id:ingredients[j]}, function (err, docs,j,i) { 
                    var ingredientscomplet = docs[0];
                    var toto= tata*ingredientscomplet.nombre;
                    ingredientscomplet.nombre = toto;
                    result.push(ingredientscomplet);
                    if (i==listedecourses.length && j==ingredients.length){res.json(result);};
                    }); 
                }

        });
    };  
});         

But for some reason, I can't access to i and j, so my last condition is never true, and i can't get my json back.

  • You can access them, they just don't have the values you expect when you do, because by the time the asynchronous callbacks happen, those loops have already completed. See the linked question's answers for more. – T.J. Crowder Feb 12 '17 at 19:37
  • (With any recent version of NodeJS, the simplest change to make it work is just to swap `let` for `var` in both `for` loops: `for (let i = ...` and `for (let j = ...`) – T.J. Crowder Feb 12 '17 at 19:38

0 Answers0