无黑客解决方案
承诺将包含在下一个Javascript版本中
流行的Promise库为您提供了
.all()一种用于这种确切用例的方法(等待一堆异步调用完成,然后执行其他操作)。这是您的方案的完美匹配
蓝鸟还具有
.map(),可以接受一组值并将其用于启动Promise链。
这是使用Bluebird的示例
.map():
var Promise = require('bluebird');var request = Promise.promisifyAll(require('request'));function processAllFeeds(feedsToFetch) { return Promise.map(feedsToFetch, function(feed){ // I renamed your 'feed' fn to 'processFeed' return processFeed(feed) }) .then(function(articles){ // 'articles' is now an array w/ results of all 'processFeed' calls // do something with all the results... }) .catch(function(e){ // feed server was down, etc })}function processFeed(feed) { // use the promisified version of 'get' return request.getAsync(feed.url)... }还要注意,您无需在此处使用闭包来累积结果。
在蓝鸟API文档都写得很好过,有很多的例子,所以它可以更容易回升。
一旦我了解了Promise模式,它就会使生活变得更加轻松。我不能推荐它。
另外,这是 一篇很棒的文章, 介绍了使用promise,
async模块和其他方法处理异步函数的不同方法
希望这可以帮助!



