Skip to content

Commit

Permalink
added asyncMap and asyncMapSeries from async.js
Browse files Browse the repository at this point in the history
  • Loading branch information
Caolan McMahon committed Dec 1, 2010
1 parent 8921d31 commit db282db
Show file tree
Hide file tree
Showing 2 changed files with 91 additions and 0 deletions.
59 changes: 59 additions & 0 deletions test/async.js
Original file line number Diff line number Diff line change
Expand Up @@ -137,4 +137,63 @@ exports['async: asyncEachSeries alias'] = function (test) {
test.done();
};

exports['async: asyncMap'] = function(test){
var call_order = [];
_.asyncMap([1,3,2], function(x, callback){
setTimeout(function(){
call_order.push(x);
callback(null, x*2);
}, x*25);
}, function(err, results){
test.same(call_order, [1,2,3]);
test.same(results, [2,6,4]);
test.done();
});
};

exports['async: asyncMap original untouched'] = function(test){
var a = [1,2,3];
_.asyncMap(a, function(x, callback){
callback(null, x*2);
}, function(err, results){
test.same(results, [2,4,6]);
test.same(a, [1,2,3]);
test.done();
});
};

exports['async: asyncMap error'] = function(test){
test.expect(1);
_.asyncMap([1,2,3], function(x, callback){
callback('error');
}, function(err, results){
test.equals(err, 'error');
});
setTimeout(test.done, 50);
};

exports['async: asyncMapSeries'] = function(test){
var call_order = [];
_.asyncMapSeries([1,3,2], function(x, callback){
setTimeout(function(){
call_order.push(x);
callback(null, x*2);
}, x*25);
}, function(err, results){
test.same(call_order, [1,3,2]);
test.same(results, [2,6,4]);
test.done();
});
};

exports['async: asyncMapSeries error'] = function(test){
test.expect(1);
_.asyncMapSeries([1,2,3], function(x, callback){
callback('error');
}, function(err, results){
test.equals(err, 'error');
});
setTimeout(test.done, 50);
};

})(typeof exports === 'undefined' ? this['async_tests'] = {}: exports);
32 changes: 32 additions & 0 deletions underscore.js
Original file line number Diff line number Diff line change
Expand Up @@ -759,6 +759,38 @@
};


var doParallel = function (fn) {
return function () {
var args = Array.prototype.slice.call(arguments);
return fn.apply(null, [_.asyncForEach].concat(args));
};
};
var doSeries = function (fn) {
return function () {
var args = Array.prototype.slice.call(arguments);
return fn.apply(null, [_.asyncForEachSeries].concat(args));
};
};


var _asyncMap = function (eachfn, arr, iterator, callback) {
var results = [];
arr = _.map(arr, function (x, i) {
return {index: i, value: x};
});
eachfn(arr, function (x, callback) {
iterator(x.value, function (err, v) {
results[x.index] = v;
callback(err);
});
}, function (err) {
callback(err, results);
});
};
_.asyncMap = doParallel(_asyncMap);
_.asyncMapSeries = doSeries(_asyncMap);


// The OOP Wrapper
// ---------------

Expand Down

0 comments on commit db282db

Please sign in to comment.