从异步请求循环中获取值

时间:2015-07-31 23:20:56

标签: javascript node.js asynchronous xmlhttprequest deferred

我正在尝试编写一个nodejs程序,用于查询github以获取repos列表(通​​过github API的节点包装器:https://www.npmjs.com/package/github)并检索数组中的git clone url,然后我希望按字母顺序排序。

由于调用的异步性质,我不确定如何等到所有异步请求都被返回?

这是有问题的循环。 repoArray是[username / reponame]格式的回购数组

var urls = [];

for (var i=0; i < repoArray.length; i++) {

    var components = repoArray[i].split('/');

    github.repos.get({
        user: components[0],
        repo: components[1]
    }, function(err, res) {
        urls.push(res.ssh_url);
    });
}

// do a case-insensitive sort
urls.sort(function(a,b) {
    return a.localeCompare(b, 'en', {'sensitivity': 'base'});
});

console.log("urls: " + urls);

基本上,因为循环中的github.repos.get()调用都是异步/回调的,当代码到达urls.sort()然后是console.log(),没有或者某些github。 repos.get()调用已经完成。

我对承诺或延期并不熟悉,但这是要走的路吗?我不确定如何重构该循环,以便只有在所有来自循环的请求完成后才调用urls.sort()?

1 个答案:

答案 0 :(得分:1)

Async库适用于这些场景,通常是人们倾向于使用这些问题。它可以帮助您并行执行异步任务,并在完成后使用async.each执行回调。

var async = require('async');
var urls = [];

//make each HTTP request
function process(repo,callback){    
  var components = repo.split('/');

  github.repos.get({
    user: components[0],
    repo: components[1]
  }, function(err, res) {
    if(err){
      // call callback(err) if there is an error
      return callback(err);
    }
    else{
      urls.push(res.ssh_url);
      // call callback(null) if it was a success,
      return callback(null);
    }
  });

}

// this will iterate over repoArray and pass each repo to the 'process' function.  
// if any of the calls to 'process' result in an error, 
// the final callback will be immediately called with an error object
async.each(repoArray,process,function(error){
  if(error){
    console.error('uh-oh: '+error)
    return;
  }
  else{
    // do a case-insensitive sort
    urls.sort(function(a,b) {
      return a.localeCompare(b, 'en', {'sensitivity': 'base'});
    });
    console.log("urls: " + urls);
  }
});

编辑:因为你在最后对它们进行排序,所以网址将按顺序排列。

相关问题