在回调中访问索引

时间:2013-07-15 22:02:04

标签: javascript node.js

所以,我有这个NodeJS代码:

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});
            });

        }

问题是,当getChallenges调用该函数时,索引处于断点,我需要仅在最后一次getChallenge回调时调用res.render。有没有办法做到这一点?感谢!!!

2 个答案:

答案 0 :(得分:0)

i包装在一个闭包中:

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

这为每次迭代创建i的本地副本,以便每个回调都绑定到其对应的i

答案 1 :(得分:0)

在函数范围之外使用索引变量并在回调中递增它:

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 });
    }
  });
}