-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
222 lines (191 loc) · 6.47 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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
var uP = require('uP');
(function(root){
"use strict";
function Promise(obj){
if(!(this instanceof Promise))
return new Promise(obj);
for(var key in obj){
this[key] = obj[key];
}
return uP(this);
}
/**
* Makes a process/function asynchronous.
* The process may also return a promise itself which to wait on.
* If the process returns undefined the promise will remain pending.
*
* Example: Make readFileSync async
* fs = require('fs');
* var asyncReadFile = p.async(fs.readFileSync,'./index.js');
* asyncReadFile.then(function(data){
* console.log(data.toString())
* },function(error){
* console.log("Read error:", error);
* });
*
* @return {Object} promise
* @api public
*/
Promise.prototype.async = function(){
var args = Array.prototype.slice.call(arguments),
proc = args.shift();
this.defer(function(){
proc.apply(null,args);
});
return this;
};
/**
* Adapted for processes expecting a callback(err,ret).
*
* Example: make readFile async
* fs = require('fs');
* var asyncReadFile = p.async2(fs.readFile,'./index.js');
* asyncReadFile.then(function(data){
* console.log(data.toString())
* },function(error){
* console.log("Read error:", error);
* });
*
* @return {Object} promise
* @api public
*/
Promise.prototype.async2 = function(){
var self = this,
args = Array.prototype.slice.call(arguments);
function callback(err,ret){ if(!e) self.fulfill(ret); else self.reject(ret); }
args[args.length] = callback;
return this.async.apply(this,args);
};
/**
* Joins promises and assembles return values into an array.
* If any of the promises rejects the rejection handler is called with the error.
*
* Example: join two promises
* p = Promise();
* a = Promise();
* b = Promise();
* p.join([a,b]).spread(function(x,y){
* console.log('a=%s, b=%s',x,y);
* },function(err){
* console.log('error=',e);
* });
* b.fulfill('world');
* a.fulfill('hello'); // => 'a=hello, b=world'
* p.resolved; // => ['hello','world']
*
* @param {Array} promises
* @return {Object} promise
* @api public
*/
Promise.prototype.join = function(promises){
var val = [],
promise = this,
chain = uP().fulfill();
if( arguments.length > 1) {
promises = Array.prototype.slice.call(arguments);
}
if(!Array.isArray(promises)) promises = [promises];
function collect(i){
promises[i].then(function(v){
val[i] = v;
});
return function(){return promises[i]}
}
for(var i = 0, l = promises.length; i < l; i++){
chain = chain.then(collect(i));
}
chain.then(function(){promise.fulfill(val)},function(e){promise.reject(e)});
return this;
};
/**
* Wraps a `proto`
*
* Example: wrap an Array
* p = Promise();
* c = p.wrap(Array);
* c(1,2,3); // => calls constructor and fulfills promise
* p.resolved; // => [1,2,3]
*
* @param {Object} proto
* @return {Object} promise
* @api public
*/
Promise.prototype.wrap = function(proto){
var promise = this;
return function(){
var args = Array.prototype.slice.call(arguments), ret;
if(proto instanceof Promise){
proto.fulfill(args).then(promise.fulfill,promise.reject);
} else if(typeof proto === 'function'){
try{
ret = proto.apply(promise,args);
if(promise.isPending) promise.fulfill(ret);
} catch(err) {
promise.reject(err);
}
}
return promise;
}
};
/**
* Spread has the same semantic as then() but splits multiple fulfillment values into separate arguments
*
* Example: Fulfillment array elements as arguments
* var p = Promise();
* p.fulfill([1,2,3]).spread(function(a,b,c){
* console.log(a,b,c); // => '1 2 3'
* });
*
* @param {Function} onFulfill
* @param {Function} onReject
* @return {Object} promise for chaining
* @api public
*/
Promise.prototype.spread = function(f,r,n){
function s(v){
if(!Array.isArray(v)) v = [v];
return f.apply(f,v);
}
return this.then(s,r,n);
};
/**
* Timeout a pending promise and invoke callback function on timeout.
* Without a callback it throws a RangeError('exceeded timeout').
*
* Example: timeout & abort()
* var p = Promise();
* p.attach({abort:function(msg){console.log('Aborted:',msg)}});
* p.timeout(5000);
* // ... after 5 secs ... => Aborted: |RangeError: 'exceeded timeout']
*
* Example: cancel timeout
* p.timeout(5000);
* p.timeout(null); // timeout cancelled
*
* @param {Number} time timeout value in ms or null to clear timeout
* @param {Function} callback optional timeout function callback
* @throws {RangeError} If exceeded timeout
* @return {Object} promise
* @api public
*/
Promise.prototype.timeout = function(t,ontimeout){
var promise = this;
if(t === null) {
clearTimeout(promise.timer);
promise.timer = null;
} else if(!promise.timer){
promise.timer = setTimeout(t,timeoutHandler);
}
function timeoutHandler(){
if(promise.isPending) {
if(typeof ontimeout === 'function') ontimeout(promise);
else throw RangeError("exceeded timeout");
}
}
return this;
};
try { root = global } catch(e) { try { root = window } catch(e) {} }
if(module && module.exports) module.exports = Promise;
else if(typeof define ==='function' && define.amd) define(Promise);
else root.Promise = Promise;
}(this));