-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
780 lines (678 loc) · 20.4 KB
/
index.js
File metadata and controls
780 lines (678 loc) · 20.4 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
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
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
/*global require, global, window */
/**
* @provides A+ v1.1 compliant promises.
* @module Promise
* @name microPromise
* @main Promise
*/
(function(root){
"use strict";
var task = require('microtask'); // nextTick shim
try {root = window;} catch(e){ try {root = global;} catch(f){} }
var slice = Array.prototype.slice,
isArray = Array.isArray;
var PENDING = 0,
FULFILLED = 1,
REJECTED = 2;
/**
* Promise constructor
*
* @param {Object} [mixin] - Mixin promise into object
* @param {Function} [resolver] - Resolver function(resolve,reject)
* @return {Object} Promise
* @api public
*/
function Promise(o){
var self = this;
// object mixin
if(o && typeof o === 'object'){
for(var k in Promise.prototype)
o[k] = Promise.prototype[k];
o._promise = {_chain:[]};
return o;
}
// create new instance
if(!(this instanceof Promise))
return new Promise(o);
this._promise = {_chain: []};
// use resolver callback
if(typeof o === 'function') {
task(function(){
var res = self.resolve.bind(self),
rej = self.reject.bind(self);
o(res,rej);
});
}
}
/**
* Helper for identifying a promise-like objects or functions
*
* @param {Object} p - Object or Function to test
* @return {Boolean} - Returns true if thenable or else false
*/
Promise.thenable = function(p){
var then;
if(p && (typeof p === 'object' || typeof p === 'function')){
try { then = p.then; } catch (e) { return false; };
}
return (typeof then === 'function');
};
/**
* Wrap a promise around function or constructor
*
* Example: wrap an Array
* p = Promise.wrap(Array);
*
* var r = c(1,2,3); // => calls Array constructor and returns fulfilled promise
* r.valueOf(); // => [1,2,3];
* @param {Function} class - class to wrap
* @param {Object} [instance] - optional instance
* @return {Function} function to wrap
* @throw {Error} on not wrappable
* @api public
*/
Promise.wrap = function(Klass,inst){
var p = new Promise();
if(!Klass) throw Error("Nothing to wrap!");
return function(){
var KC = Klass.prototype.constructor,
args = slice.call(arguments),
ret;
if(typeof KC === 'function'){
try {
ret = KC.apply(inst,args);
if(!(ret instanceof Klass)){
KC = function(){};
KC.prototype = Klass.prototype;
inst = new KC();
try {
ret = Klass.apply(inst,args);
} catch (e){
p.reject(e);
return;
}
ret = Object(ret) === ret ? ret : inst;
}
p.resolve(ret);
} catch(err){
p.reject(err);
}
} else throw Error("not wrappable");
return p;
};
};
/**
* Deferres a task and returns a pending promise fulfilled with the return value from task.
* The task may also return a promise itself which to wait on.
*
* Example: Make readFileSync async
* fs = require('fs');
* var asyncReadFile = Promise().defer(fs.readFileSync,'./index.js','utf-8');
* asyncReadFile.then(function(data){
* console.log(data)
* },function(error){
* console.log("Read error:", error);
* });
*
* @param {Function} - task to defer
* @param {...} [args] - optional list of arguments
* @return {Object} - returns a pending promise
* @api public
*/
Promise.defer = function(){
var args = slice.call(arguments),
f = args.shift(),
p = new Promise();
if(typeof f === 'function'){
task(enclose,args);
}
function enclose(){
try {
p.resolve(f.apply(p,args));
} catch(err) {
p.reject(err);
}
}
return p;
};
/**
* Make function asyncronous and fulfill/reject promise on execution.
*
* Example: make readFile async
* fs = require('fs');
* var asyncReadFile = Promise.async(fs.readFile);
* asyncReadFile('package.json','utf8').then(function(data){
* console.log(data);
* },function(error){
* console.log("Read error:", error);
* });
*
* @param {Function} function - function to make async
* @param {Function} [callback] - optional callback to call
* @return {Object} promise
* @api public
*/
Promise.async = function(func,cb){
var p = new Promise(), called;
if(typeof func !=='function')
throw new TypeError("func is not a function");
cb = typeof cb === 'function' ? cb : function (err,ret){
called = true;
if(err) p.reject(err);
else if(err === 0) p.progress(ret);
else p.fulfill(ret);
};
return function(){
var args = slice.call(arguments);
args.push(cb);
task(function(){
var ret;
try {
ret = func.apply(null,args);
} catch(err) {
cb(err);
}
if(ret !==undefined && !called) {
if(ret instanceof Error) cb(ret);
else cb(undefined,ret);
}
});
return p;
};
};
/**
* Check if promise is pending
*
* @return {Boolean} - Returns true if pending or else false
*/
Promise.prototype.isPending = function(){
return !this._promise._state;
};
/**
* Check if promise is fulfilled
*
* @return {Boolean} - Returns true if pending or else false
*/
Promise.prototype.isFulfilled = function(){
return this._promise._state === FULFILLED;
};
/**
* Check if promise is rejeced
*
* @return {Boolean} - Returns true if pending or else false
*/
Promise.prototype.isRejected = function(){
return this._promise._state === REJECTED;
};
/**
* Check if promise has resolved
*
* @return {Boolean} - Returns true if pending or else false
*/
Promise.prototype.hasResolved = function(){
return !!this._promise._state;
};
/**
* Get value if promise has been fulfilled
*
* @return {Boolean} - Returns true if pending or else false
*/
Promise.prototype.valueOf = function(){
return this.isFulfilled() ? this._promise._value : undefined;
};
/**
* Get reason if promise has rejected
*
* @return {Boolean} - Returns true if pending or else false
*/
Promise.prototype.reason = function(){
return this.isRejected() ? this._promise._value : undefined;
};
/**
* Attaches callback,errback,notify handlers and returns a promise
*
* Example: catch fulfillment or rejection
* var p = Promise();
* p.then(function(value){
* console.log("received:", value);
* },function(error){
* console.log("failed with:", error);
* });
* p.fulfill('hello world!'); // => 'received: hello world!'
*
* Example: chainable then clauses
* p.then(function(v){
* console.log('v is:', v);
* if(v > 10) throw new RangeError('to large!');
* return v*2;
* }).then(function(v){
* // gets v*2 from above
* console.log('v is:', v)
* },function(e){
* console.log('error2:', e);
* });
* p.fulfill(142); // => v is: 142, error2: [RangeError:'to large']
*
* Example: undefined callbacks are ignored
* p.then(function(v){
* if(v < 0) throw v;
* return v;
* }).then(undefined,function(e){
* e = -e;
* return e;
* }).then(function(value){
* console.log('we got:', value);
* });
* p.fulfill(-5); // => we got: 5
*
* @param {Function} onFulfill callback
* @param {Function} onReject errback
* @param {Function} onNotify callback
* @return {Object} a decendant promise
* @api public
*/
Promise.prototype.then = function(f,r,n){
var p = new Promise(), self = this._promise;
self._chain[self._chain.length] = [p,f,r,n];
if(self._state) task(traverse,[self]);
return p;
};
/**
* Like `then` but spreads array into multiple arguments
*
* Example: Multiple fulfillment values
* p = Promise();
* p.fulfill([1,2,3])
* p.spread(function(a,b,c){
* console.log(a,b,c); // => '1 2 3'
* });
*
* @param {Function} onFulfill callback
* @param {Function} onReject errback
* @param {Function} onNotify callback
* @return {Object} a decendant promise
* @api public
*/
Promise.prototype.spread = function(f,r,n){
function s(v,a){
if(!isArray(v)) v = [v];
return f.apply(f,v.concat(a));
}
return this.then(s,r,n);
};
/**
* Terminates chain of promises, calls onerror or throws on unhandled Errors
*
* Example: capture error with done
* p.then(function(v){
* console.log('v is:', v);
* if(v > 10) throw new RangeError('to large!');
* return v*2;
* }).done(function(v){
* // gets v*2 from above
* console.log('v is:', v)
* });
*
* p.fulfill(142); // => v is: 142, throws [RangeError:'to large']
*
* Example: define onerror handler defined on promise
* p.onerror = function(error){ console.log("Sorry:",error) };
* p.then(function(v){
* console.log('v is:', v);
* if(v > 10) throw new RangeError('to large!');
* return v*2;
* }).done(function(v){
* // gets v*2 from above
* console.log('v is:', v)
* });
* p.fulfill(142); // => v is: 142, "Sorry: [RangeError:'to large']"
*
* @param {Function} onFulfill callback
* @param {Function} onReject errback
* @param {Function} onNotify callback
* @api public
*/
Promise.prototype.done = function(f,r,n){
var self = this, p = this.then(f,catchError,n);
function catchError(e){
task(function(){
if(typeof r === 'function') r(e);
else if(typeof self.onerror === 'function'){
self.onerror(e);
} else if(Promise.onerror === 'function'){
Promise.onerror(e);
} else throw e;
});
}
};
/**
* Terminates chain, invokes a callback or throws Error on error
*
* @param {Function} callback - Callback with value or Error object on error.
* @api public
*/
Promise.prototype.end = function(callback){
this.then(callback,function(e){
if(!(e instanceof Error)){
e = new Error(e);
}
if(typeof callback === 'function') callback(e);
else throw e;
});
};
/**
* Catches errors, terminates promise chain and calls errBack handler.
*
*
* Example: Catch error
* p = Promise();
* p.then(function(v){
* console.log("someone said:", v); //-> "Hello there"
* return "boom!";
* })
* .then(function(v){ if(v === 'boom!') throw "something bad happened!";})
* .catch(function(e){
* console.log("error:",e);
* });
* p.resolve("Hello there");
*
* @param {Function} onError callback
* @return undefined
* @api public
*/
Promise.prototype.catch = function(errBack){
this.done(undefined,errBack);
};
/**
* Fulfills a promise with a `value`
*
*
* Example: fulfillment
* p = Promise();
* p.fulfill(123);
*
* Example: multiple fulfillment values in array
* p = Promise();
* p.fulfill([1,2,3]);
* p.resolved; // => [1,2,3]
*
* Example: Pass through opaque arguments (experimental)
* p = Promise();
* p.fulfill("hello","world");
* p.then(function(x,o){
* console.log(x,o[0]); // => "hello world"
* o.push("!");
* return "bye bye";
* }).then(function(x,o){
* console.log(x,o.join('')); // => "bye bye world!"
* })
*
* @param {Object} value
* @return {Object} promise
* @api public
*/
Promise.prototype.fulfill = function(value,opaque){
var self = this._promise;
if(!self._state) {
self._state = FULFILLED;
self._value = value;
self._opaque = opaque;
task(traverse,[self]);
}
return this;
};
/**
* Rejects promise with a `reason`
*
* Example:
* p = Promise();
* p.then(function(ok){
* console.log("ok:",ok);
* }, function(error){
* console.log("error:",error);
* });
* p.reject('some error'); // outputs => 'error: some error'
*
* @param {Object} reason
* @return {Object} promise
* @api public
*/
Promise.prototype.reject = function(reason,opaque){
var self = this._promise;
if(self._state === undefined){
self._state = REJECTED;
self._value = reason;
self._opaque = opaque;
task(traverse,[self,REJECTED,reason,opaque]);
}
return this;
};
/**
* Resolves a promise and performs unwrapping if necessary
*
*
* Example: resolve a literal
* p = Promise();
* p.resolve(123); // fulfills promise to 123
*
* Example: resolve value from pending promise
* p1 = Promise();
* p2 = Promise();
* p1.resolve(p2);
* p2.fulfill(123) // => p1 fulfills to 123
*
* @param {Object} value - Promise or literal
* @return {Object} promise
* @api public
*/
Promise.prototype.resolve = function(x,o){
var then, z = 0, self = this._promise, p = this;
if(!self._state){
if(x === p) p.reject(new TypeError("Promise cannot resolve itself!"));
if(x && (typeof x === 'object' || typeof x === 'function')){
try { then = x.then; } catch(e){ p.reject(e); }
}
if(typeof then !== 'function'){
p.fulfill(x,o);
} else if(!z){
try {
then.apply(x,[function(y){
if(!z) {
p.resolve(y,o);
z = 1;
}
},function(r){
if(!z) {
p.reject(r);
z = 1;
}
}]);
} catch(e) {
if(!z) {
p.reject(e);
z = 1;
}
}
}
}
return this;
};
/**
* Notifies attached handlers
*
* Example:
* p = Promise();
* p.then(function(ok){
* console.log("ok:",ok);
* }, function(error){
* console.log("error:",error);
* }, function(notify){
* console.log(notify);
* });
* p.progress("almost done"); // optputs => 'almost done'
* p.reject('some error'); // outputs => 'error: some error'
*
* @param {Object} arguments
* @api public
*/
Promise.prototype.progress = function(){
var notify, chain = this._promise._chain;
for(var i = 0, l = chain.length; i < l; i++){
if(typeof (notify = chain[i][2]) === 'function')
notify.apply(this,arguments);
}
};
/**
* 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.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
* @throw {RangeError} If timeout exceeded
* @return {Object} promise
* @api public
*/
Promise.prototype.timeout = function(msec,func){
var p = this, self = this._promise;
if(msec === null) {
if(self._timeout)
root.clearTimeout(self._timeout);
self._timeout = null;
} else if(!self._timeout){
self._timeout = root.setTimeout(onTimeout,msec);
}
function onTimeout(){
var e = new RangeError("exceeded timeout");
if(!self._state) {
if(typeof func === 'function') func(p);
else if(typeof p.onerror === 'function') p.onerror(e);
else throw e;
}
}
return this;
};
/**
* Resolves promise to a nodejs styled callback function(err,ret)
* and passes the callbacks return value down the chain.
*
* Example:
* function cb(err,ret){
* if(err) console.log("error(%s):",err,ret);
* else console.log("success:", ret);
*
* return "nice";
* }
*
* p = Promise();
* p.callback(cb)
* .then(function(cbret){
* console.log("callback says:", cbret); //-> callback says: nice
* });
*
* p.fulfill("ok"); //-> success: ok
*
* @param {Function} callback - Callback function
* @return {Object} promise
* @api public
*/
Promise.prototype.callback = function(callback){
return this.then(function(value,opaque){
return callback(undefined,value,opaque);
},function(reason,opaque){
var error = reason;
if(!(error instanceof Error)){
if(typeof reason === 'object'){
error = new Error(JSON.stringify(reason));
for(var k in reason)
error[k] = reason[k];
} else {
error = new Error(reason);
}
}
return callback(error,opaque);
},function(progress){
return callback(0,progress);
});
};
/**
* Joins promises and collects results into an array.
* If any of the promises are rejected the chain is also rejected.
*
* Example: join with two promises
* a = Promise();
* b = Promise();
* c = Promise();
* a.join([b,c]).spread(function(a,b,c){
* console.log(a,b,c);
* },function(err){
* console.log('error=',err);
* });
* b.fulfill('world');
* a.fulfill('hello');
* c.fulfill('!'); // => 'hello world !''
*
* @param {Array} promises
* @return {Object} promise
* @api public
*/
Promise.prototype.join = function(j){
var p = this,
y = [],
u = new Promise().resolve(p).then(function(v){y[0] = v;});
if(arguments.length > 1) {
j = slice.call(arguments);
}
if(!isArray(j)) j = [j];
function stop(error){
u.reject(error);
}
function collect(i){
j[i].then(function(v){
y[i+1] = v;
}).catch(stop);
return function(){return j[i];};
}
for(var i = 0; i < j.length; i++){
u = u.then(collect(i));
}
return u.then(function(){return y;});
};
// Resolver function, yields a promised value to handlers
function traverse(_promise){
var c = _promise._chain,
s = _promise._state,
v = _promise._value,
o = _promise._opaque,
t, p, h, r;
while((t = c.shift())){
p = t[0];
h = t[s];
if(typeof h === 'function') {
try {
r = h(v,o);
p.resolve(r,o);
} catch(e) {
p.reject(e);
}
} else {
p._promise._state = s;
p._promise._value = v;
p._promise._opaque = o;
task(traverse,[p._promise]);
}
}
}
/* expose this module */
if(module && module.exports) module.exports = Promise;
else if(typeof define ==='function' && define.amd) define(Promise);
else root.Promise = Promise;
}(this));