如何有可变数量的蓝鸟承诺? (的NodeJS)

我有一个空的文件数组。

let arrayOfDocuments = []; 

我想调用http请求(使用superagent)来下载一个文本文件,并将其内容放入我的arrayOfDocuments。

 request.get('docs.google.com/document/d/SOME_FILE_NAME').then((res) => { arrayOfDocuments.push(res.text); }); 

我得到的那部分,但这是棘手的部分。 我想把它放在一个for循环中,并在for循环之后做一些事情。 如此:

 for (let i = 0; i < numOfLinks; i++) { // send the http requests as above } //do stuff here but only after the above for loop is finished. 

如果循环结束,我只能做最后一行? 现在我的程序运行的方式,for循环之后的代码在http请求得到响应之前运行并完成。 我认为有一种方法可以使用蓝鸟诺言做到这一点,但我不确定。 谢谢!

使用promise.all ,如http://bluebirdjs.com/docs/api/promise.all.html所&#x793A;

在实践中,它可能看起来像这样:

 var promises = [] var links = ['a.com/a', 'a.com/b'] for (let i = 0; i < links.length; i++) { promises.push(request.get(links[i]) } Promise.all(promises).then(function(allRes) { //do anything you want with allRes or iterate for (var promise in promises){ promise.then(function(singleRes){/*do something with each promise after all resolve*/} } }); 

您可以使用Promise.map方法:

 Promise.map(arrayOfLinks, function(link) { return request.get(link); }).then(function(arrayOfDocuments) { // ... });