-
Notifications
You must be signed in to change notification settings - Fork 86
Expand file tree
/
Copy pathfastq.js
More file actions
85 lines (71 loc) · 1.86 KB
/
fastq.js
File metadata and controls
85 lines (71 loc) · 1.86 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
'use strict';
/**
* @class FastQ
*
* @description
*
* Synchronous promise implementation (partial)
*
*/
RMModule.factory('RMFastQ', ['$q', function($q) {
var isFunction = angular.isFunction,
catchError = function(_error) {
return this.then(null, _error);
};
function simpleQ(_val, _withError) {
if(_val && isFunction(_val.then)) return wrappedQ(_val);
return {
simple: true,
then: function(_success, _error) {
return simpleQ(_withError ? _error(_val) : _success(_val));
},
'catch': catchError,
'finally': function(_cb) {
var result = _cb();
if(result && isFunction(_val.then)) {
// if finally returns a promise, then
return wrappedQ(_val.then(
function() { return _withError ? simpleQ(_val, true) : _val; },
function() { return _withError ? simpleQ(_val, true) : _val; })
);
} else {
return this;
}
}
};
}
function wrappedQ(_promise) {
if(_promise.simple) return _promise;
var simple;
// when resolved, make $q a simpleQ
_promise.then(function(_val) {
simple = simpleQ(_val);
}, function(_val) {
simple = simpleQ(_val, true);
});
return {
then: function(_success, _error) {
return simple ?
simple.then(_success, _error) :
wrappedQ(_promise.then(_success, _error));
},
'catch': catchError,
'finally': function(_cb) {
return simple ?
simple['finally'](_cb) :
wrappedQ(_promise['finally'](_cb));
}
};
}
return {
reject: function(_reason) {
return simpleQ(_reason, true);
},
// non waiting promise, if resolved executes immediately
when: function(_val) {
return simpleQ(_val, false);
},
wrap: wrappedQ,
defer: $q.defer
};
}]);