0

I now use this code (part of my code):

async.forEachOfSeries(dates, function(mydate, m, eachDone) { 
        eachDateParse(Name,Place,Strategy, eachDone)
}, function(err) {
    if (err) throw err;
    console.log("All Done!");
    callback(); }
); 

async.forEachOfSeries does loop over dates in order, but is there any async function that can randomise the order of the loop over dates?

Best Regards

user1665355
  • 3,324
  • 8
  • 44
  • 84
  • You'd probably have to randomly shuffle `dates` yourself before you iterate over it, making this a dupe of -> [How to randomize (shuffle) a JavaScript array](http://stackoverflow.com/questions/2450954/how-to-randomize-shuffle-a-javascript-array) – adeneo Dec 12 '15 at 17:37
  • @adeneo Yes, but dont want to use that solution whenever possible. Is there any async library function for that? – user1665355 Dec 12 '15 at 17:38
  • 1
    I don't think there is, the whole point of async.js is to be able to run asynchronous methods in series, parallell, waterfalls etc. and keep order, not randomize it, then you might as well not use async.js at all. – adeneo Dec 12 '15 at 17:40
  • 1
    May be useful: https://lodash.com/docs#shuffle – Shanoor Dec 12 '15 at 17:48
  • If you want to stick to async.js only you could attach a property with random number do each object of `dates` and use `sortBy` function before your code. Also if `dates` is a collection I think you should use the `each` method and without `Series` as you do not care about execution order. – kriskot Dec 12 '15 at 18:17
  • @kriskot do you have an example maybe?:) can accept then – user1665355 Dec 12 '15 at 18:25

1 Answers1

2

This is an example for my comment as requested

var dates = ['20110101', '20120101', '20130101', '20140101', '20150101'];

async.sortBy(dates, function(item, callback) {
    callback(null, Math.random());
}, function(err, result) {
    console.log('Sorting is finished.');
    async.each(result, function(date, callback) {
        console.log('Parsing date: ' + date);
        callback();
    }, function(error, res) {
        console.log('All dates are parsed now.');
    });
});

although I'm not quite sure if nesting async functions is a good idea it seems to be working.

kriskot
  • 303
  • 1
  • 8