0

所以,我有这个 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});
            });

        }

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

4

2 回答 2

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.

于 2013-07-15T22:09:39.190 回答
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 });
    }
  });
}
于 2013-07-15T23:42:55.860 回答