forked from 3rd-Eden/versions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
async.js
75 lines (63 loc) · 1.61 KB
/
async.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
'use strict';
function noop() {}
/**
* Return the fastest result, ignoring errors.
*
* @param {Array} collection
* @param {Function} iterator
* @param {Mixed} context
* @param {Function} callback
* @api public
*/
exports.fastest = function fastest(collection, iterator) {
var callback, context, failure
, length = collection.length
, completed = 0;
if (arguments.length === 4) {
context = arguments[2];
callback = arguments[3];
} else {
callback = arguments[2];
}
callback = callback || noop;
collection.forEach(function forEach(item) {
iterator.call(context, item, function iterating(err) {
if (!err) {
callback.apply(context, arguments);
callback = noop;
}
if (++completed === length) {
callback.call(context);
}
});
});
};
/**
* Keep iterating over the array in series until we find a response without an
* error.
*
* @param {Array} collection
* @param {Function} iterator
* @param {Mixed} context
* @param {Function} callback
* @api public
*/
exports.failover = function failover(collection, iterator, complete) {
var callback, context, failure
, length = collection.length
, completed = 0;
if (arguments.length === 4) {
context = arguments[2];
callback = arguments[3];
} else {
callback = arguments[2];
}
callback = callback || noop;
(function series() {
if (!collection.length) return callback.call(context);
iterator.call(context, collection.shift(), function iterator(err) {
if (!err) return callback.apply(context, arguments);
process.nextTick(series);
});
})();
};