-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
89 lines (74 loc) · 1.56 KB
/
index.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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
/*!
* any - index.js
* Copyright(c) 2014 dead_horse <[email protected]>
* MIT Licensed
*/
'use strict';
/**
* Module dependencies.
*/
var toThunk = require('back-to-thunk');
/**
* slice() reference.
*/
var slice = Array.prototype.slice;
/**
* Expose `any`
*/
module.exports = any;
/**
* Execute thunks in parallel and return after any of them return
* support
* any(f1, f2, f3)
* any([f1, f2, f3])
* @return {Thunk}
* @api public
*/
function any(obj) {
var ctx = this;
if (typeof obj === 'function') {
obj = slice.call(arguments);
}
return function(done) {
var keys = Object.keys(obj);
var isArray = Array.isArray(obj);
var finished;
function getkey(key) {
return isArray ? Number(key) : key;
}
if (!keys.length) {
setImmediate(function() {
done(null, null);
});
return;
}
for (var i = 0; i < keys.length; i++) {
run(obj[keys[i]], keys[i]);
}
function run(fn, key) {
if (finished) return;
try {
fn = toThunk(fn, ctx);
if (typeof fn !== 'function') {
done(new Error('co.any only accept yieldables'));
}
fn.call(ctx, function(err, res) {
if (finished) return;
finished = true;
if (err) {
err._key = getkey(key);
return done(err);
}
done(null, {
_key: getkey(key),
value: res
});
});
} catch (err) {
finished = true;
err._key = getkey(key);
done(err);
}
}
}
}