So, I have this NodeJS code:
for(var i = 0; i < subcats.length; i++) {
subcats[i].getChallenges(function(challenges) {
this.challenges = challenges;
if(index == subcats.length - 1)
res.render('challenges/category', {'category': category, 'subcats': subcats});
});
}
The issue is that by the time getChallenges calls the function, the index is at its breaking point and I need to call res.render on only the last getChallenge callback. Is there any way to do this? Thanks!!!
Just wrap i in a closure:
(function(i) {
// 'i' here is a copy --
// it will keep the same value, even after the outer loop increments its own 'i'
subcats[i].getChallenges(function(challenges) {
this.challenges = challenges;
if(index == subcats.length - 1)
res.render('challenges/category', {'category': category, 'subcats': subcats});
});
}(i));
This creates a local copy of i for each iteration, so that each callback will be bound to its corresponding i.
Use index variable out of the functions scope and increment it in callbacks:
var completed = 0;
for(var i = 0, len = subcats.length; i < len; i++) {
subcats[i].getChallenges(function(challenges) {
this.challenges = challenges;
if(++completed == len) {
res.render('challenges/category', { 'category': category, 'subcats': subcats });
}
});
}