你可以用蓝鸟的Promise.mapSeries http://bluebirdjs.com/docs/api/promise.mapseries.html:
var files = [
'file1',
'file2'
];
var result = Promise.mapSeries(files, function(file) {
return downloadFile(file); // << the return must be a promise
});
根据您用来下载文件的内容,您可能必须做出承诺或不做出承诺。
Update 1
一个例子downloadFile()
仅使用nodejs的功能:
var http = require('http');
var path = require('path');
var fs = require('fs');
function downloadFile(file) {
console.time('downloaded in');
var name = path.basename(file);
return new Promise(function (resolve, reject) {
http.get(file, function (res) {
res.on('data', function (chunk) {
fs.appendFileSync(name, chunk);
});
res.on('end', function () {
console.timeEnd('downloaded in');
resolve(name);
});
});
});
}
Update 2
正如 Gorgi Kosev 所建议的,使用循环构建承诺链也有效:
var p = Promise.resolve();
files.forEach(function(file) {
p = p.then(downloadFile.bind(null, file));
});
p.then(_ => console.log('done'));
承诺链只会为您提供链中最后一个承诺的结果,而mapSeries()
为您提供一个包含每个承诺结果的数组。