Nid*_*vid 8 javascript node.js underscore.js lodash bluebird
我有一个数组,每个索引包含文件名.我想一次下载一个文件(同步).我知道' Async'模块.但我想知道Lodash或Underscore或Bluebird库中的任何函数是否支持此功能.
你可以使用蓝鸟Promise.mapSeries:
var files = [
'file1',
'file2'
];
var result = Promise.mapSeries(files, function(file) {
return downloadFile(file); // << the return must be a promise
});
Run Code Online (Sandbox Code Playgroud)
根据您用于下载文件的内容,您可能需要构建承诺.
更新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);
});
});
});
}
Run Code Online (Sandbox Code Playgroud)
更新2
正如Gorgi Kosev所建议的,使用循环建立一系列承诺也是有效的:
var p = Promise.resolve();
files.forEach(function(file) {
p = p.then(downloadFile.bind(null, file));
});
p.then(_ => console.log('done'));
Run Code Online (Sandbox Code Playgroud)
一连串的承诺只会让您获得链中最后一个承诺的结果,同时mapSeries()为您提供一个包含每个承诺结果的数组.
| 归档时间: |
|
| 查看次数: |
2194 次 |
| 最近记录: |