Iterate the array synchronously using lodash, underline, or bluebird

I have an array containing file names for each index. I want to download these files one at a time (synchronously). I know about the Async module. But I want to know if any functions in the Lodash or Underscore or Bluebird library Lodash this function.

+8
javascript lodash bluebird
source share
2 answers

You can use bluebird 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 the file, you may have to work out a promise or not.

Update 1

Example 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); }); }); }); } 

Update 2

As suggested by Gorgi Kosev, creating a chain of promises using a loop too:

 var p = Promise.resolve(); files.forEach(function(file) { p = p.then(downloadFile.bind(null, file)); }); p.then(_ => console.log('done')); 

The promise chain will only give you the result of the last promise in the chain, and mapSeries() will give you an array with the result of each promise.

+4
source share

using Bluebird, there is a situation similar to yours with the answer here: How to bind a variable number of promises in Q, okay?

This seems like a decent solution, but, in my opinion, much less readable and elegant, like async.eachSeries (I know that you said that you do not want a โ€œasynchronousโ€ solution, but maybe you can reconsider.

+1
source share

All Articles