如何将索引传递给嵌套在for循环中的回调?

时间:2015-06-13 00:38:43

标签: javascript node.js concurrency callback scope

我正在编写一个Node.js模块,该模块查询GitHub API以找出哪个用户的repos有一个gh-pages分支。这是代码:

// index.js
var https = require('https');
var spawn = require('child_process').spawn;

module.exports = function(user, auth_token) {
    // Normally this would be another API call but I'm simplifying
    var repos = ['android', 'colortime.js', 'strugee.github.com'];

    for (var i in repos) {
        var repo = repos[i];
        console.log('running for loop with repo =', repo);

        https.get({
            hostname: 'api.github.com',
            path: '/repos/strugee/' + repo + '/branches',
            headers: {'User-Agent': 'gh-pages-bootstrap/1.0.0', Authorization: 'token ' + auth_token}
        }, function(res) {
            console.log('calling https callback with repo =', repo);
        });
    }
};

我已将此模块放在CLI包装器中(包含源代码,以便您可以更轻松地测试模块):

// cli.js
var ghauth = require('ghauth');
var ghpages = require('./index.js');

var authOptions = {
    configName: 'gh-pages-bootstrap',
    scopes: ['public_repo'],
    note: 'gh-pages-bootstrap',
    userAgent: 'gh-pages-bootstrap/1.0.0'
};

ghauth(authOptions, function(err, authData) {
    if (err) throw err;
    ghpages(authData.user, authData.token);
});

吐出以下内容:

running for loop with repo = android
running for loop with repo = colortime.js
running for loop with repo = strugee.github.com
calling https callback with repo = strugee.github.com
calling https callback with repo = strugee.github.com
calling https callback with repo = strugee.github.com

正如您所看到的,回调始终认为repo是一回事。显然问题是,当收到响应头并且触发回调时,for循环已经完成。然而,尽管有这方面的知识,但我不能为我的生活弄清楚如何让回调使用repo的正确值。至少,不是没有阻止事件循环(这显然是不理想的)。

我很确定我错过了关于变量范围的一些规则,我认为原型模型可能涉及到某种东西,这非常令人困惑。

如何解决这个并发问题?

0 个答案:

没有答案