<分区>
我有一个数组,每个索引都包含文件名。我想一次一个(同步)下载这些文件。我知道“Async
”模块。但我想知道 Lodash
或 Underscore
或 Bluebird
库中是否有任何函数支持此功能。
<分区>
我有一个数组,每个索引都包含文件名。我想一次一个(同步)下载这些文件。我知道“Async
”模块。但我想知道 Lodash
或 Underscore
或 Bluebird
库中是否有任何函数支持此功能。
最佳答案
您可以使用 Bluebird 的 Promise.mapSeries
:
var files = [
'file1',
'file2'
];
var result = Promise.mapSeries(files, function(file) {
return downloadFile(file); // << the return must be a promise
});
根据您使用什么下载文件,您可能需要构建一个 promise 或不构建一个 promise 。
更新 1
仅使用 nodejs 的 downloadFile()
函数示例:
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);
});
});
});
}
更新 2
正如 Gorgi Kosev 所建议的,使用循环构建 promise 链也很有效:
var p = Promise.resolve();
files.forEach(function(file) {
p = p.then(downloadFile.bind(null, file));
});
p.then(_ => console.log('done'));
promise 链只会让您获得链中最后一个 promise 的结果,而 mapSeries()
会为您提供一个包含每个 promise 结果的数组。
关于javascript - 如何使用 lodash、underscore 或 bluebird 同步迭代数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34436129/