-
Notifications
You must be signed in to change notification settings - Fork 28
/
yaku.core.js
774 lines (667 loc) · 22 KB
/
yaku.core.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
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
/**
* This is the minimal implementation of Yaku.
* No extra helper methods.
*/
(function () {
'use strict';
var $undefined
, $null = null
, isBrowser = typeof self === 'object'
, root = isBrowser ? self : global
, nativePromise = root.Promise
, process = root.process
, Arr = Array
, $rejected = 0
, $resolved = 1
, $pending = 2
, $Symbol = 'Symbol'
, $iterator = 'iterator'
, $species = 'species'
, $speciesKey = $Symbol + '(' + $species + ')'
, $return = 'return'
, $unhandled = '_uh'
, $invalidThis = 'Invalid this'
, $invalidArgument = 'Invalid argument'
, $promiseCircularChain = 'Chaining cycle detected for promise'
, $rejectionHandled = 'rejectionHandled'
, $unhandledRejection = 'unhandledRejection'
, $tryCatchFn
, $tryCatchThis
, $tryErr = { e: $null }
, $noop = function () {}
, Symbol = root[$Symbol] || {}
, nextTick = isBrowser ?
function (fn) {
nativePromise ?
new nativePromise(function (resolve) { resolve(); }).then(fn) :
setTimeout(fn);
} :
process.nextTick
, speciesConstructor = function (O, D) {
var C = O.constructor;
return C ? (C[getSpecies()] || D) : D;
}
;
/**
* This class follows the [Promises/A+](https://promisesaplus.com) and
* [ES6](http://people.mozilla.org/~jorendorff/es6-draft.html#sec-promise-objects) spec
* with some extra helpers.
* @param {Function} executor Function object with two arguments resolve, reject.
* The first argument fulfills the promise, the second argument rejects it.
* We can call these functions, once our operation is completed.
*/
var Yaku = function Promise (executor) {
var self = this,
err;
// "this._s" is the internal state of: pending, resolved or rejected
// "this._v" is the internal value
if (!isObject(self) || self._s !== $undefined)
throw genTypeError($invalidThis);
self._s = $pending;
if (executor !== $noop) {
if (!isFunction(executor))
throw genTypeError($invalidArgument);
err = genTryCatcher(executor)(
genSettler(self, $resolved),
genSettler(self, $rejected)
);
if (err === $tryErr)
settlePromise(self, $rejected, err.e);
}
};
Yaku['default'] = Yaku;
extendPrototype(Yaku, {
/**
* Appends fulfillment and rejection handlers to the promise,
* and returns a new promise resolving to the return value of the called handler.
* @param {Function} onFulfilled Optional. Called when the Promise is resolved.
* @param {Function} onRejected Optional. Called when the Promise is rejected.
* @return {Yaku} It will return a new Yaku which will resolve or reject after
* @example
* the current Promise.
* ```js
* var Promise = require('yaku');
* var p = Promise.resolve(10);
*
* p.then((v) => {
* console.log(v);
* });
* ```
*/
then: function then (onFulfilled, onRejected) {
if (this._s === undefined) throw genTypeError();
return addHandler(
this,
newCapablePromise(speciesConstructor(this, Yaku)),
onFulfilled,
onRejected
);
},
/**
* The `catch()` method returns a Promise and deals with rejected cases only.
* It behaves the same as calling `Promise.prototype.then(undefined, onRejected)`.
* @param {Function} onRejected A Function called when the Promise is rejected.
* This function has one argument, the rejection reason.
* @return {Yaku} A Promise that deals with rejected cases only.
* @example
* ```js
* var Promise = require('yaku');
* var p = Promise.reject(new Error("ERR"));
*
* p['catch']((v) => {
* console.log(v);
* });
* ```
*/
'catch': function (onRejected) {
return this.then($undefined, onRejected);
},
/**
* Register a callback to be invoked when a promise is settled (either fulfilled or rejected).
* Similar with the try-catch-finally, it's often used for cleanup.
* @param {Function} onFinally A Function called when the Promise is settled.
* It will not receive any argument.
* @return {Yaku} A Promise that will reject if onFinally throws an error or returns a rejected promise.
* Else it will resolve previous promise's final state (either fulfilled or rejected).
* @example
* ```js
* var Promise = require('yaku');
* var p = Promise.reject(new Error("ERR"));
*
* p['catch']((v) => {
* console.log(v);
* });
* ```
*/
'finally': function (onFinally) {
return this.then(function (val) {
return Yaku.resolve(onFinally()).then(function () {
return val;
});
}, function (err) {
return Yaku.resolve(onFinally()).then(function () {
throw err;
});
});
},
// The number of current promises that attach to this Yaku instance.
_pCount: 0,
// The parent Yaku.
_pre: $null,
// A unique type flag, it helps different versions of Yaku know each other.
_Yaku: 1
});
/**
* The `Promise.resolve(value)` method returns a Promise object that is resolved with the given value.
* If the value is a thenable (i.e. has a then method), the returned promise will "follow" that thenable,
* adopting its eventual state; otherwise the returned promise will be fulfilled with the value.
* @param {Any} value Argument to be resolved by this Promise.
* Can also be a Promise or a thenable to resolve.
* @return {Yaku}
* @example
* ```js
* var Promise = require('yaku');
* var p = Promise.resolve(10);
* ```
*/
Yaku.resolve = function resolve (val) {
return isYaku(val) ? val : settleWithX(newCapablePromise(this), val);
};
/**
* The `Promise.reject(reason)` method returns a Promise object that is rejected with the given reason.
* @param {Any} reason Reason why this Promise rejected.
* @return {Yaku}
* @example
* ```js
* var Promise = require('yaku');
* var p = Promise.reject(new Error("ERR"));
* ```
*/
Yaku.reject = function reject (reason) {
return settlePromise(newCapablePromise(this), $rejected, reason);
};
/**
* The `Promise.race(iterable)` method returns a promise that resolves or rejects
* as soon as one of the promises in the iterable resolves or rejects,
* with the value or reason from that promise.
* @param {iterable} iterable An iterable object, such as an Array.
* @return {Yaku} The race function returns a Promise that is settled
* the same way as the first passed promise to settle.
* It resolves or rejects, whichever happens first.
* @example
* ```js
* var Promise = require('yaku');
* Promise.race([
* 123,
* Promise.resolve(0)
* ])
* .then((value) => {
* console.log(value); // => 123
* });
* ```
*/
Yaku.race = function race (iterable) {
var self = this
, p = newCapablePromise(self)
, resolve = function (val) {
settlePromise(p, $resolved, val);
}
, reject = function (val) {
settlePromise(p, $rejected, val);
}
, ret = genTryCatcher(each)(iterable, function (v) {
self.resolve(v).then(resolve, reject);
});
if (ret === $tryErr) return self.reject(ret.e);
return p;
};
/**
* The `Promise.all(iterable)` method returns a promise that resolves when
* all of the promises in the iterable argument have resolved.
*
* The result is passed as an array of values from all the promises.
* If something passed in the iterable array is not a promise,
* it's converted to one by Promise.resolve. If any of the passed in promises rejects,
* the all Promise immediately rejects with the value of the promise that rejected,
* discarding all the other promises whether or not they have resolved.
* @param {iterable} iterable An iterable object, such as an Array.
* @return {Yaku}
* @example
* ```js
* var Promise = require('yaku');
* Promise.all([
* 123,
* Promise.resolve(0)
* ])
* .then((values) => {
* console.log(values); // => [123, 0]
* });
* ```
* @example
* Use with iterable.
* ```js
* var Promise = require('yaku');
* Promise.all((function * () {
* yield 10;
* yield new Promise(function (r) { setTimeout(r, 1000, "OK") });
* })())
* .then((values) => {
* console.log(values); // => [123, 0]
* });
* ```
*/
Yaku.all = function all (iterable) {
var self = this
, p = newCapablePromise(self)
, res = []
, ret
;
function reject (reason) {
settlePromise(p, $rejected, reason);
}
ret = genTryCatcher(each)(iterable, function (item, i) {
self.resolve(item).then(function (value) {
res[i] = value;
if (!--ret) settlePromise(p, $resolved, res);
}, reject);
});
if (ret === $tryErr) return self.reject(ret.e);
if (!ret) settlePromise(p, $resolved, []);
return p;
};
/**
* The `Promise.allSettled(iterable)` method returns a promise that resolves after all
* of the given promises have either resolved or rejected, with an array of objects that
* each describes the outcome of each promise.
* @param {iterable} iterable An iterable object, such as an Array.
* @return {Yaku} A promise resolves a list of objects. For each object, a status string is present.
* If the status is fulfilled, then a value is present. If the status is rejected, then a reason is present.
* The value (or reason) reflects what value each promise was fulfilled (or rejected) with.
* @example
* ```js
* var Promise = require('yaku');
* Promise.allSettled([
* Promise.resolve(3),
* new Promise((resolve, reject) => setTimeout(reject, 100, 'foo'))
* ])
* .then((values) => {
* console.log(values); // => [{status: "fulfilled", value: 3}, {status: "rejected", reason: "foo"}]
* });
* ```
*/
Yaku.allSettled = function (iterable) {
var self = this
, p = newCapablePromise(self)
, res = []
, ret
;
ret = genTryCatcher(each)(iterable, function (item, i) {
self.resolve(item).then(function (value) {
res[i] = { status: 'fulfilled', value: value };
if (!--ret) settlePromise(p, $resolved, res);
}, function (value) {
res[i] = { status: 'rejected', reason: value };
if (!--ret) settlePromise(p, $resolved, res);
});
});
if (ret === $tryErr) return self.reject(ret.e);
if (!ret) settlePromise(p, $resolved, []);
return p;
};
// To support browsers that don't support `Object.defineProperty`.
genTryCatcher(function () {
Object.defineProperty(Yaku, getSpecies(), {
get: function () { return this; }
});
})();
// ********************** Private **********************
Yaku._Yaku = 1;
/**
* All static variable name will begin with `$`. Such as `$rejected`.
* @private
*/
// ******************************* Utils ********************************
function getSpecies () {
return Symbol[$species] || $speciesKey;
}
function extendPrototype (src, target) {
for (var k in target) {
src.prototype[k] = target[k];
}
return src;
}
function isObject (obj) {
return obj && typeof obj === 'object';
}
function isFunction (obj) {
return typeof obj === 'function';
}
function isInstanceOf (a, b) {
return a instanceof b;
}
function ensureType (obj, fn, msg) {
if (!fn(obj)) throw genTypeError(msg);
}
/**
* Wrap a function into a try-catch.
* @private
* @return {Any | $tryErr}
*/
function tryCatcher () {
try {
return $tryCatchFn.apply($tryCatchThis, arguments);
} catch (e) {
$tryErr.e = e;
return $tryErr;
}
}
/**
* Generate a try-catch wrapped function.
* @private
* @param {Function} fn
* @return {Function}
*/
function genTryCatcher (fn, self) {
$tryCatchFn = fn;
$tryCatchThis = self;
return tryCatcher;
}
/**
* Generate a scheduler.
* @private
* @param {Integer} initQueueSize
* @param {Function} fn `(Yaku, Value) ->` The schedule handler.
* @return {Function} `(Yaku, Value) ->` The scheduler.
*/
function genScheduler (initQueueSize, fn) {
/**
* All async promise will be scheduled in
* here, so that they can be execute on the next tick.
* @private
*/
var fnQueue = Arr(initQueueSize)
, fnQueueLen = 0;
/**
* Run all queued functions.
* @private
*/
function flush () {
var i = 0;
while (i < fnQueueLen) {
fn(fnQueue[i], fnQueue[i + 1]);
fnQueue[i++] = $undefined;
fnQueue[i++] = $undefined;
}
fnQueueLen = 0;
if (fnQueue.length > initQueueSize) fnQueue.length = initQueueSize;
}
return function (v, arg) {
fnQueue[fnQueueLen++] = v;
fnQueue[fnQueueLen++] = arg;
if (fnQueueLen === 2) nextTick(flush);
};
}
/**
* Generate a iterator
* @param {Any} obj
* @private
* @return {Object || TypeError}
*/
function each (iterable, fn) {
var len
, i = 0
, iter
, item
, ret
;
if (!iterable) throw genTypeError($invalidArgument);
var gen = iterable[Symbol[$iterator]];
if (isFunction(gen))
iter = gen.call(iterable);
else if (isFunction(iterable.next)) {
iter = iterable;
}
else if (isInstanceOf(iterable, Arr)) {
len = iterable.length;
while (i < len) {
fn(iterable[i], i++);
}
return i;
} else
throw genTypeError($invalidArgument);
while (!(item = iter.next()).done) {
ret = genTryCatcher(fn)(item.value, i++);
if (ret === $tryErr) {
isFunction(iter[$return]) && iter[$return]();
throw ret.e;
}
}
return i;
}
/**
* Generate type error object.
* @private
* @param {String} msg
* @return {TypeError}
*/
function genTypeError (msg) {
return new TypeError(msg);
}
// *************************** Promise Helpers ****************************
/**
* Resolve the value returned by onFulfilled or onRejected.
* @private
* @param {Yaku} p1
* @param {Yaku} p2
*/
var scheduleHandler = genScheduler(999, function (p1, p2) {
var x, handler;
// 2.2.2
// 2.2.3
handler = p1._s ? p2._onFulfilled : p2._onRejected;
// 2.2.7.3
// 2.2.7.4
if (handler === $undefined) {
settlePromise(p2, p1._s, p1._v);
return;
}
// 2.2.7.1
x = genTryCatcher(callHanler)(handler, p1._v);
if (x === $tryErr) {
// 2.2.7.2
settlePromise(p2, $rejected, x.e);
return;
}
settleWithX(p2, x);
});
var scheduleUnhandledRejection = genScheduler(9, function (p) {
if (!hashOnRejected(p)) {
p[$unhandled] = 1;
emitEvent($unhandledRejection, p);
}
});
function emitEvent (name, p) {
var browserEventName = 'on' + name.toLowerCase()
, browserHandler = root[browserEventName];
if (process && process.listeners(name).length)
name === $unhandledRejection ?
process.emit(name, p._v, p) : process.emit(name, p);
else if (browserHandler)
browserHandler({ reason: p._v, promise: p });
}
function isYaku (val) { return val && val._Yaku; }
function newCapablePromise (Constructor) {
if (isYaku(Constructor)) return new Constructor($noop);
var p, r, j;
p = new Constructor(function (resolve, reject) {
if (p) throw genTypeError();
r = resolve;
j = reject;
});
ensureType(r, isFunction);
ensureType(j, isFunction);
return p;
}
/**
* It will produce a settlePromise function to user.
* Such as the resolve and reject in this `new Yaku (resolve, reject) ->`.
* @private
* @param {Yaku} self
* @param {Integer} state The value is one of `$pending`, `$resolved` or `$rejected`.
* @return {Function} `(value) -> undefined` A resolve or reject function.
*/
function genSettler (self, state) {
var isCalled = false;
return function (value) {
if (isCalled) return;
isCalled = true;
if (state === $resolved)
settleWithX(self, value);
else
settlePromise(self, state, value);
};
}
/**
* Link the promise1 to the promise2.
* @private
* @param {Yaku} p1
* @param {Yaku} p2
* @param {Function} onFulfilled
* @param {Function} onRejected
*/
function addHandler (p1, p2, onFulfilled, onRejected) {
// 2.2.1
if (isFunction(onFulfilled))
p2._onFulfilled = onFulfilled;
if (isFunction(onRejected)) {
if (p1[$unhandled]) emitEvent($rejectionHandled, p1);
p2._onRejected = onRejected;
}
p1[p1._pCount++] = p2;
// 2.2.6
if (p1._s !== $pending)
scheduleHandler(p1, p2);
// 2.2.7
return p2;
}
// iterate tree
function hashOnRejected (node) {
// A node shouldn't be checked twice.
if (node._umark)
return true;
else
node._umark = true;
var i = 0
, len = node._pCount
, child;
while (i < len) {
child = node[i++];
if (child._onRejected || hashOnRejected(child)) return true;
}
}
function callHanler (handler, value) {
// 2.2.5
return handler(value);
}
/**
* Resolve or reject a promise.
* @private
* @param {Yaku} p
* @param {Integer} state
* @param {Any} value
*/
function settlePromise (p, state, value) {
var i = 0
, len = p._pCount;
// 2.1.2
// 2.1.3
if (p._s === $pending) {
// 2.1.1.1
p._s = state;
p._v = value;
if (state === $rejected) {
scheduleUnhandledRejection(p);
}
// 2.2.4
while (i < len) {
scheduleHandler(p, p[i++]);
}
}
return p;
}
/**
* Resolve or reject promise with value x. The x can also be a thenable.
* @private
* @param {Yaku} p
* @param {Any | Thenable} x A normal value or a thenable.
*/
function settleWithX (p, x) {
// 2.3.1
if (x === p && x) {
settlePromise(p, $rejected, genTypeError($promiseCircularChain));
return p;
}
// 2.3.2
// 2.3.3
if (x !== $null && (isFunction(x) || isObject(x))) {
// 2.3.2.1
var xthen = genTryCatcher(getThen)(x);
if (xthen === $tryErr) {
// 2.3.3.2
settlePromise(p, $rejected, xthen.e);
return p;
}
if (isFunction(xthen)) {
// Fix https://bugs.chromium.org/p/v8/issues/detail?id=4162
if (isYaku(x))
settleXthen(p, x, xthen);
else
nextTick(function () {
settleXthen(p, x, xthen);
});
} else
// 2.3.3.4
settlePromise(p, $resolved, x);
} else
// 2.3.4
settlePromise(p, $resolved, x);
return p;
}
/**
* Try to get a promise's then method.
* @private
* @param {Thenable} x
* @return {Function}
*/
function getThen (x) { return x.then; }
/**
* Resolve then with its promise.
* @private
* @param {Yaku} p
* @param {Thenable} x
* @param {Function} xthen
*/
function settleXthen (p, x, xthen) {
// 2.3.3.3
var err = genTryCatcher(xthen, x)(function (y) {
// 2.3.3.3.3
// 2.3.3.3.1
x && (x = $null, settleWithX(p, y));
}, function (r) {
// 2.3.3.3.3
// 2.3.3.3.2
x && (x = $null, settlePromise(p, $rejected, r));
});
// 2.3.3.3.4.1
if (err === $tryErr && x) {
// 2.3.3.3.4.2
settlePromise(p, $rejected, err.e);
x = $null;
}
}
try {
module.exports = Yaku;
} catch (e) {
root.Yaku = Yaku;
}
})();