Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

async.race() method #1018

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 46 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -215,6 +215,7 @@ Some functions are also available in the following forms:
* [`retry`](#retry)
* [`iterator`](#iterator)
* [`times`](#times), `timesSeries`, `timesLimit`
* [`race`](#race)

### Utils

Expand Down Expand Up @@ -1446,7 +1447,7 @@ __Arguments__
* `opts` - Can be either an object with `times` and `interval` or a number.
* `times` - The number of attempts to make before giving up. The default is `5`.
* `interval` - The time to wait between retries, in milliseconds. The default is `0`.
* If `opts` is a number, the number specifies the number of times to retry, with the default interval of `0`.
* If `opts` is a number, the number specifies the number of times to retry, with the default interval of `0`.
* `task(callback, results)` - A function which receives two arguments: (1) a `callback(err, result)`
which must be called when finished, passing `err` (which can be `null`) and the `result` of
the function's execution, and (2) a `results` object, containing the results of
Expand All @@ -1464,14 +1465,14 @@ async.retry(3, apiMethod, function(err, result) {
```

```js
// try calling apiMethod 3 times, waiting 200 ms between each retry
// try calling apiMethod 3 times, waiting 200 ms between each retry
async.retry({times: 3, interval: 200}, apiMethod, function(err, result) {
// do something with the result
});
```

```js
// try calling apiMethod the default 5 times no delay between each retry
// try calling apiMethod the default 5 times no delay between each retry
async.retry(apiMethod, function(err, result) {
// do something with the result
});
Expand Down Expand Up @@ -1641,6 +1642,47 @@ __Related__
* timesSeries(n, iterator, [callback])
* timesLimit(n, limit, iterator, [callback])


---------------------------------------

<a name="race" />
### race(tasks, [callback])

Runs the `tasks` array of functions in parallel, without waiting until the
previous function has completed. Once any the `tasks` completed or pass an
error to its callback, the main `callback` is immediately called. It's
equivalent to `Promise.race()`.

__Arguments__

* `tasks` - An array containing functions to run. Each function is passed
a `callback(err, result)` which it must call on completion with an error `err`
(which can be `null`) and an optional `result` value.
* `callback(err, result)` - A callback to run once any of the
functions have completed. This function gets an error or result from the
first function that completed.

__Example__

```js
async.race([
function(callback){
setTimeout(function(){
callback(null, 'one');
}, 200);
},
function(callback){
setTimeout(function(){
callback(null, 'two');
}, 100);
}
],
// main callback
function(err, result){
// the result will be equal to 'two' as it finishes earlier
});
```

---------------------------------------

<a name="memoize"></a>
Expand Down Expand Up @@ -1792,7 +1834,7 @@ async.waterfall([
return db.model.create(contents);
}),
function (model, next) {
// `model` is the instantiated model object.
// `model` is the instantiated model object.
// If there was an error, this function would be skipped.
}
], callback)
Expand Down
23 changes: 22 additions & 1 deletion lib/async.js
Original file line number Diff line number Diff line change
Expand Up @@ -1090,7 +1090,7 @@
var memoized = _restParam(function memoized(args) {
var callback = args.pop();
var key = hasher.apply(null, args);
if (has.call(memo, key)) {
if (has.call(memo, key)) {
async.setImmediate(function () {
callback.apply(null, memo[key]);
});
Expand Down Expand Up @@ -1247,6 +1247,27 @@
});
};

async.race = function (tasks, callback) {
callback = _once(callback || noop);
if (!_isArray(tasks)) {
return callback(new TypeError('First argument to waterfall must be an array of functions'));
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

typo, change waterfall to race

}
if (!tasks.length) {
return callback(null);
}
for (var i = 0; i < tasks.length; i++) {
tasks[i](only_once(done));
}
var called = false;
function done(err, result) {
if (called) {
return;
}
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

no need for called or this condition. once will handle it

called = true;
callback(err, result);
}
};

// Node.js
if (typeof module === 'object' && module.exports) {
module.exports = async;
Expand Down
67 changes: 67 additions & 0 deletions mocha_test/race.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
var async = require('../lib/async');
var assert = require('assert');

describe('race', function () {
it('should call each function in parallel and callback with first result', function (done) {
var finished = 0;
var tasks = [];
for (var i = 0; i < 10; i++) {
tasks[i] = (function () {
var index = i;
return function (next) {
finished++;
next(null, index);
}
})();
}
async.race(tasks, function (err, result) {
assert.ifError(err);
//0 finished first
assert.strictEqual(result, 0);
assert.strictEqual(finished, 1);
async.setImmediate(function () {
assert.strictEqual(finished, 10);
done();
});
});
});
it('should callback with the first error', function (done) {
var tasks = [];
for (var i = 0; i <= 5; i++) {
tasks[i] = (function () {
var index = i;
return function (next) {
setTimeout(function () {
next(new Error('ERR' + index));
}, 50 - index * 2);
}
})();
}
async.race(tasks, function (err, result) {
assert.ok(err);
assert.ok(err instanceof Error);
assert.strictEqual(typeof result, 'undefined');
assert.strictEqual(err.message, 'ERR5');
done();
});
});
it('should callback when task is empty', function (done) {
async.race([], function (err, result) {
assert.strictEqual(err, null);
assert.strictEqual(typeof result, 'undefined');
done();
});
});
it('should callback in error the task arg is not an Array', function () {
var errors = [];
async.race(null, function (err) {
errors.push(err);
});
async.race({}, function (err) {
errors.push(err);
});
assert.strictEqual(errors.length, 2);
assert.ok(errors[0] instanceof TypeError);
assert.ok(errors[1] instanceof TypeError);
});
});