如何使用 lodash、underscore 或 bluebird 同步迭代数组 [关闭]

2024-05-12

我有一个数组,其中每个索引处包含文件名。我想下载这些文件一次一个(同步)。我知道关于'Async' 模块。但我想知道是否有任何功能Lodash or Underscore or Bluebird库支持此功能。


你可以用蓝鸟的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()为您提供一个包含每个承诺结果的数组。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使用 lodash、underscore 或 bluebird 同步迭代数组 [关闭] 的相关文章

随机推荐