/
aplus.extras.js
96 lines (79 loc) · 2.12 KB
/
aplus.extras.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
90
91
92
93
94
95
96
// resolve all given promises to a single promise
Aplus.pool = function() {
// get promises
var promises = Array.slice.call(arguments, 0);
var state = 1;
var values = new Array(promises.length);
var toGo = promises.length;
// promise to return
var promise = Aplus();
// whenever a promise completes
var checkFinished = function() {
// check if all the promises have returned
if (toGo) {
return;
}
// set the state with all values if all are complete
promise.changeState(state, values);
};
// whenever a promise finishes check to see if they're all finished
for (var i = 0; i < promises.length; i++) {
(function(index) {
promises[index].then(function(value) {
// on success
values[index] = value;
toGo--;
checkFinished();
}, function(value) {
// on error
values[index] = value;
toGo--;
// set error state
state = 2;
checkFinished();
});
})(i);
};
// promise at the end
return promise;
};
// return the value of the first succesful promise
Aplus.first = function() {
// get all promises
var promises = Array.slice.call(arguments, 0);
// promise to return
var promise = Aplus();
// if all promises error out then we want to return an error
Aplus.pool.apply(Aplus, promises).then(undefined, function(value) {
promise.reject(value);
});
// when there is a success we want to fulfill the promise
var success = function(value) {
promise.fulfill(value);
};
// listen for success on all promises
for (var i = 0; i < promises.length; i++) {
promises[i].then(success);
}
return promise;
};
// take a callback function and change it to return a promise
Aplus.toPromise = function(fn) {
return function() {
// promise to return
var promise = Aplus();
//on error we want to reject the promise
var errorFn = function(data) {
promise.reject(data);
};
// fulfill on success
var successFn = function(data) {
promise.fulfill(data);
};
// run original function with the error and success functions
// that will set the promise state when done
fn.apply(this,
[errorFn, successFn].concat(Array.slice.call(arguments, 0)));
return promise;
};
};