如何使用lodash,underscore或bluebird同步迭代数组 [英] How to iterate an array synchronously using lodash, underscore or bluebird

查看:123
本文介绍了如何使用lodash,underscore或bluebird同步迭代数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数组,每个索引都包含文件名。我想一次下载这些文件(同步)。我知道' Async '模块。但我想知道 Lodash Underscore Bluebird 库支持此功能。

I have an array that contains filenames at each index. I want to download those files one at a time (synchronously). I know about 'Async' module. But I want to know whether any functions in Lodash or Underscore or Bluebird library supports this functionality.

推荐答案

您可以使用bluebird的 Promise.mapSeries

You can use bluebird's Promise.mapSeries:

var files = [
    'file1',
    'file2'
];

var result = Promise.mapSeries(files, function(file) {
    return downloadFile(file); // << the return must be a promise
});

根据您用来下载文件的内容,您可能需要建立或不承诺。

Depending on what you use to download file, you may have to build a promise or not.

更新1

downloadFile()的例子仅使用nodejs的函数:

An exemple of a downloadFile() function using only 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);
            });
        });
    });
}

更新2

正如Gorgi Kosev建议的那样,使用循环构建一系列承诺也是有效的:

As Gorgi Kosev suggested, building a chain of promises using a loop works too:

var p = Promise.resolve();
files.forEach(function(file) {
    p = p.then(downloadFile.bind(null, file));
});

p.then(_ => console.log('done'));

承诺链只能获得链中最后一个承诺的结果,而 mapSeries()为您提供一个包含每个承诺结果的数组。

A chain of promise will get you only the result of the last promise in the chain while mapSeries() gives you an array with the result of each promise.

这篇关于如何使用lodash,underscore或bluebird同步迭代数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆