-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathasync.js
More file actions
104 lines (86 loc) · 2.84 KB
/
async.js
File metadata and controls
104 lines (86 loc) · 2.84 KB
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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
// module
var Async = {}
Async.Continuation = function(method) {
var continuation = {
method: method,
args: Array.prototype.slice.call(arguments, 1)
};
continuation.exec = function(callback) {
continuation.method.apply(null, continuation.args.concat(callback));
}
continuation.then = function(makeDo) {
return Async.Continuation(function(callback) {
continuation.exec(function(err) {
if (err != null) callback(err);
else {
var results = Array.prototype.slice.call(arguments, 1);
makeDo.apply(continuation, results).exec(callback);
}
});
});
}
continuation.print = function() {
continuation.exec(function(err, result) {
console.log(err, result);
});
}
return continuation;
}
Async.Fail = function(err) {
var fail = function(message, callback) {
return callback(message);
}
return Async.Continuation(fail, err);
}
Async.Sequence = function(makers, initial) {
return makers.reduce(function(continuation, maker) {
return continuation.then(maker);
}, Async.Identity(initial));
}
Async.Parallel = function(builders, initial) {
return Async.Continuation(function(callback) {
var numComplete = 0;
var errs = null;
var results = null;
var complete = function(err, result) {
if (err) errs = (errs || []).concat(err);
if (result) results = (results || []).concat(result);
numComplete++;
if (numComplete == builders.length) {
return callback(errs, results);
}
}
builders.forEach(function(builder) {
builder(initial).exec(complete);
});
});
}
Async.Reduce = function(array, transform) {
return array.reduce(function(continuation, element) {
return continuation.then(function(accumulation) {
function async(callback) {
function complete(err, result) {
if (err) callback(err);
else callback(null, accumulation.concat(result));
}
return Async.Continuation(transform, element).exec(complete);
}
return Async.Continuation(async);
});
}, Async.Identity([]));
}
Async.Map = function(array, transform) {
return Async.Parallel(array.map(function(element) {
return function() {
return Async.Continuation(transform, element);
}
}));
}
Async.Identity = function(value) {
return Async.Continuation(function(callback) {
callback(null, value);
});
}
// TODO
// Async.Filter, Async.If, Async.Unless, Async.Every, Async.Reject, Async.Some
// This is basically a less full-featured http://caolan.github.io/async/docs.html