-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path52.async_js.js
More file actions
2903 lines (1720 loc) · 47.1 KB
/
Copy path52.async_js.js
File metadata and controls
2903 lines (1720 loc) · 47.1 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
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// // Example 362 - setTimeout() callback
// console.log('A');
//
// setTimeout(function() {
// console.log('B');
// }, 1000);
//
// console.log('C');
//
//
// // prints A -> C -> B
// // Example 363 - setTimeout() accepts function argument
// function printMessage(msg) {
// console.log("printMessage: " + msg);
// }
//
//
// console.log('A');
//
// setTimeout(printMessage, 1000, 'B');
//
// console.log('C');
//
// // here B is the argument of printMessage using setTimeout()
// // prints A -> C -> B
// // Example 364 - setTimeout() can be cancelled before it can call the callback function
// // clearTimeout() is used to do that.
// function printMessage(msg) {
// console.log("printMessage: " + msg);
// }
//
//
// console.log('A');
//
// var timer = setTimeout(printMessage, 1000, 'B');
//
// console.log('C');
//
// clearTimeout(timer); // cleared timer, B won't be printed
// // Example 365 - timeout certain operation if it takes longer than expected
//
// // function to make a function timeout after delay milli-seconds
// function timeoutify(callback, delay) {
// var timer = setTimeout(function () {
// timer = null;
//
// callback(new Error('Timeout!'));
// }, delay);
//
//
// return function() {
// if(timer) {
// clearTimeout(timer);
// callback.apply(this, arguments);
// }
// // console.log('timeoutify returned function'); // for debugging
// };
// }
//
//
//
//
// // for debugging
// var i = 1;
// var counter = setInterval(function() {
// if(i > 10) {
// clearInterval(counter);
// return;
// }
// console.log('tick', i);
// i++;
// }, 1000);
//
//
//
// // timeout test
// setTimeout(timeoutify(function (err, data) {
// console.log('on timeout test');
// if(err) {
// console.log(err.message);
// } else {
// console.log('hello world');
// }
//
// }, 4000), 10000);
//
//
// // no timeout test
// setTimeout(timeoutify(function (err, data) {
// console.log('on success test:');
// if(err) {
// console.log(err.message);
// } else {
// console.log('hello world from success test');
// }
//
// }, 4000), 1000);
// // Example 366 - synchronous code vs asynchronous code
// // prints 1 if asynchronous, 0 if non asynchronous
// function resultSyncCallback(data) {
// console.log('sync call, result =', a);
// }
//
// function resultAsyncCallback(data) {
// console.log('async call, result =', b);
// }
//
//
// // synchronous function
// function readFile(filename, callback) {
// callback();
// }
//
//
// // sync, prints 0
// var a = 0;
// readFile('hello.txt', resultSyncCallback);
// a++;
//
//
// // async, prints 1
// var b = 0;
// setTimeout(resultAsyncCallback, 0);
// b++;
// // Example 367 - Making synchronous code run asynchronous
// // For explanation refer to Semicolon's answer at https://stackoverflow.com/questions/30383542/kyle-simpson-asyncify-function-from-you-dont-know-js-async-performance
// /* NOTE: I COPIED THE ANSWER FROM THE ABOVE LINK, SO I CAN REMIND MYSELF LATER WHEN I LOOK AT THE CODE
// * The code seems to be an very convoluted way of saying this:
//
// function asyncify(cb) {
// return function() {
// setTimeout(function() {
// cb.apply(this, arguments);
// }, 0);
// }
// }
// But I should emphasize ‘seems.’ Perhaps I’m missing some important nuance in the back-and-forth above.
//
// As for bind.apply, that’s a little trickier to explain. Both are methods on every function, which allow you to invoke it with a specified context (this) and in the case of apply, it accepts arguments as an array.
//
// When we "apply" bind, bind itself is the function which is being applied -- not the object apply lived on, which could have been anything. Therefore, it might be easier to begin making sense of this line if we rewrite it like this:
//
// Function.prototype.bind.apply(...)
// Bind has a signature like this: .bind(context, arg1, arg2...)
//
// The arguments are optional -- often they are used for currying, which is one of the main use cases for bind. In this case, the author wishes to bind the original function to (1) the current this context, (2) the arguments which the "asyncified" function was invoked with. Because we don’t know in advance how many arguments need to be passed along, we must use apply, where the arguments can be an array or an actual arguments object. Here's a very verbose rewrite of this section that may help illuminate what occurs:
//
// var contextOfApply = orig_fn;
// var contextWithWhichToCallOriginalFn = this;
//
// var argumentArray = Array.prototype.slice.call(arguments);
//
// argumentArray.unshift(contextWithWhichToCallOriginalFn);
//
// // Now argument array looks like [ this, arg1, arg2... ]
// // The 'this' is the context argument for bind, and therefore the
// // context with which the function will end up being called.
//
// fn = Function.prototype.bind.apply(contextOfApply, argumentArray);
// Actually...
//
// I can explain how the simple version I provided differs. On reviewing it again I caught what that missing nuance was that led its author to go through that weird dance at top. It is not actually a function for making another function "always async". It is a function that only ensures it is async once -- it guards against executing the callback during the same tick in which it was created but thereafter, it executes synchronously.
//
// It’s still possible to write this in a friendlier way though, I think:
//
// function asyncify(cb) {
// var inInitialTick = true;
//
// setTimeout(function() { inInitialTick = false; }, 0);
//
// return function() {
// var self = this;
// var args = arguments;
//
// if (inInitialTick)
// setTimeout(function() { cb.apply(self, args); }, 0);
// else
// cb.apply(self, args);
// }
// }
// Now I should note that the above does not actually do what it says. In fact the number of times that the function will execute using a timeout vs. synchronously is kind of random using either this or the original version. That's because setTimeout is a lame (but sometimes fine) substitute for setImmediate, which is clearly what this function really wants (but perhaps can't have, if it needs to run in Moz & Chrome).
//
// This is because the millisecond value passed to setTimeout is kind of a "soft target". It won't actually be zero; in fact it will always be at least 4ms if I recall right, meaning any number of ticks may pass.
//
// Imagining for a moment that you’re in a magical wonderland where ES6 stuff works and there’s no weird hand-wringing over whether to implement a utility as fundamental as setImmediate, it could be rewritten like this, and then it would have predictable behavior, because unlike setTimeout with 0, setImmediate really does ensure the execution occurs on the next tick and not some later one:
//
// const asyncify = cb => {
// var inInitialTick = true;
//
// setImmediate(() => inInitialTick = false);
//
// return function() {
// if (inInitialTick)
// setImmediate(() => cb.apply(this, arguments));
// else
// cb.apply(this, arguments);
// }
// };
// Actually Actually...
//
// There's one more difference. In the original, if called during the "current tick which is actually an arbitrary number of successive ticks" it will still only execute one initial time, with the final set of arguments. This actually smells a little like it might be unintended behavior, but without context I'm only guessing; this may be exactly what was intended. This is because on each call before the first timeout completes, fn is overwritten. This behavior is sometimes called throttling but in this case, unlike "normal" throttling, it will only take place for an unknown length of time around 4ms after its creation, and thereafter will be unthrottled and synchronous. Good luck to whoever has to debug the Zalgo thus invoked :)
// * */
//
// // // Easy implementation
// // function asyncify(cb) {
// // return function() {
// // setTimeout(function() {
// // cb.apply(this, arguments);
// // }, 0);
// // }
// // }
//
//
// // YDKJS implementation
// function asyncify(fn) {
// var orig_fn = fn,
// intv = setTimeout( function(){
// console.log('1');
// intv = null;
//
// if (fn) {
// console.log('2');
// fn();
// }
// }, 0 );
//
// fn = null;
//
// return function() {
// if (intv) {
// console.log('3');
// fn = orig_fn.bind.apply(orig_fn, [this].concat([].slice.call(arguments)));
// } else {
// console.log('4');
// orig_fn.apply(this, arguments);
// }
// };
// }
//
//
// function resultSyncCallback(data) {
// console.log('sync call, result =', a);
// }
//
//
//
// // sync, prints 0
// var a = 0;
// resultSyncCallback();
// a++;
//
// a = 0;
// var asyncResult = asyncify(resultSyncCallback);
// setTimeout(asyncResult, 0);
// a++;
// // Example 368 - adding program that deals with parameters not set but will be set in the future
//
// // add() works with future parameters
// function add(getX, getY, callback) {
// // x and y are future parameters
// var x;
// var y;
//
//
// console.log('getting x...');
// getX(function(xValue) {
// console.log('x value set.');
// x = xValue;
//
// if(y != undefined) {
// callback(x + y);
// }
// });
//
//
// console.log('getting y...');
// getY(function (yValue) {
// console.log('y value set.');
// y = yValue;
//
// if(x != undefined) {
// callback(x + y);
// }
// });
// }
//
//
// // returns x after 2 seconds
// function fetchX(callback) {
// setTimeout(callback, 2000, 2);
// }
//
// // return y after 1 seconds
// function fetchY(callback) {
// setTimeout(callback, 1000, 5);
// }
//
//
// // call add
// add(fetchX, fetchY, function (result) {
// console.log('result : ' + result);
// });
// // Example 369 - Example 368 in JS Promise
//
// // add() works with Promise, also returns another Promise
// /* FROM JS DOCS
// Promise.all(iterable)
// Returns a promise that either fulfills when all of the promises in the iterable argument have fulfilled or rejects as soon as one of the promises in the iterable argument rejects. If the returned promise fulfills, it is fulfilled with an array of the values from the fulfilled promises in same order as defined in the iterable. If the returned promise rejects, it is rejected with the reason from the first promise in the iterable that rejected. This method can be useful for aggregating results of multiple promises.
// */
// function add(xPromise, yPromise) {
// return Promise.all([xPromise, yPromise]).then(function (values) {
// return values[0] + values[1];
// });
// }
//
//
//
// // returns x after 2 seconds
// function fetchX(x) {
// return new Promise(function(resolve, reject) {
// setTimeout(function () {
// if(typeof x === "number") {
// return resolve(x);
// } else {
// return reject(new Error("x is invalid"));
// }
// }, 2000);
// });
// }
//
// // returns x after 1 seconds
// function fetchY(y) {
// return new Promise(function(resolve, reject) {
// setTimeout(function () {
// if(typeof y === "number") {
// return resolve(y);
// } else {
// return reject(new Error("y is invalid"));
// }
// }, 1000);
// });
// }
//
//
//
//
// // call add()
// add(fetchX(5), fetchY(10)).then(function (sum) {
// console.log('result: ' + sum);
// }, function (error) {
// console.log("Error: " + error.message);
// });
// // Example 370 - Example 369 - Promise error handling
//
// // add() works with Promise, also returns another Promise
// /* FROM JS DOCS
// Promise.all(iterable)
// Returns a promise that either fulfills when all of the promises in the iterable argument have fulfilled or rejects as soon as one of the promises in the iterable argument rejects. If the returned promise fulfills, it is fulfilled with an array of the values from the fulfilled promises in same order as defined in the iterable. If the returned promise rejects, it is rejected with the reason from the first promise in the iterable that rejected. This method can be useful for aggregating results of multiple promises.
// */
// function add(xPromise, yPromise) {
// return Promise.all([xPromise, yPromise]).then(function (values) {
// return values[0] + values[1];
// });
// }
//
//
//
// // returns x after 2 seconds
// function fetchX(x) {
// return new Promise(function(resolve, reject) {
// setTimeout(function () {
// if(typeof x === "number") {
// return resolve(x);
// } else {
// return reject(new Error("x is invalid"));
// }
// }, 2000);
// });
// }
//
// // returns x after 1 seconds
// function fetchY(y) {
// return new Promise(function(resolve, reject) {
// setTimeout(function () {
// if(typeof y === "number") {
// return resolve(y);
// } else {
// return reject(new Error("y is invalid"));
// }
// }, 1000);
// });
// }
//
//
//
// // call add() - Error handling
// add(fetchX(5), fetchY("2")).then(function (sum) {
// console.log('result: ' + sum);
// }, function (error) {
// console.log("Error: " + error.message);
// });
// // Example 371 - A Promise returned from a function is immutable and it can be passed to other function
// // as many times as desired and then these function can decide what to do on success or failure
//
// // function that returns Promise
// function addNumbers(x, y) {
// return (new Promise((resolve, reject) => {
// if(typeof x !== "number" || typeof y !== "number") {
// return reject(new Error('x and y must be numeric'));
// }
//
// return resolve(x + y);
// }));
// }
//
//
// // function that acts on the result of Promise
// function printResult(promiseObject) {
// promiseObject.then(function(result) {
// console.log('the result is: ' + result);
// }, function(error) {
// console.log('Error Message: ' + error.message);
// });
// }
//
//
// var p1 = addNumbers(5, 9);
// var p2 = addNumbers(9, 'a');
//
//
// printResult(p1);
// printResult(p2);
// // Example 372 - A Slight modification of Example 371
//
// // function that returns Promise
// function addNumbers(x, y) {
// return (new Promise((resolve, reject) => {
// if(typeof x !== "number" || typeof y !== "number") {
// return reject(new Error('inputs must be numeric'));
// }
//
// return resolve({
// value: x + y,
// x: x,
// y: y
// });
// }));
// }
//
//
// // function that acts on the result of Promise
// function printResult(promiseObject) {
// promiseObject.then(function(result) {
// console.log(result.x + ' + ' + result.y + ' = ' + result.value);
// }, function(error) {
// console.log('Error Message: ' + error.message);
// });
// }
//
//
// var p1 = addNumbers(5, 9);
// var p2 = addNumbers(9, 'a');
// var p3 = addNumbers(25, 12);
//
//
// printResult(p1);
// printResult(p2);
// printResult(p3);
// // Example 373 - Since Promises are immutable, it can be passed to many functions without any risk
//
// // function that returns Promise
// function addNumbers(x, y) {
// return (new Promise((resolve, reject) => {
// if(typeof x !== "number" || typeof y !== "number") {
// return reject(new Error('inputs must be numeric'));
// }
//
// return resolve({
// value: x + y,
// x: x,
// y: y
// });
// }));
// }
//
//
// // this Promise handler only cares about printing the result, no errors
// function handleResult(promiseObject) {
// promiseObject.then(function(result) {
// console.log(result.value);
// });
// }
//
//
// // this Promise handler cares about result and errors
// function handleResultErrors(promiseObject) {
// function success(result) {
// console.log('(' + result.x + ',' + result.y + ') = ' + result.value);
// }
//
// function failure(error) {
// console.log(error.message);
// }
//
// promiseObject.then(success, failure);
// }
//
//
// var p1 = addNumbers(5, 9);
// var p2 = addNumbers(9, 'a');
// var p3 = addNumbers(25, 12);
//
//
// handleResult(p1);
// handleResultErrors(p2);
// handleResultErrors(p3);
// // Example 374 - Since Promises are immutable, it can be handled this way as well
//
// // function that returns Promise
// function addNumbers(x, y) {
// return (new Promise((resolve, reject) => {
// if(typeof x !== "number" || typeof y !== "number") {
// return reject(new Error('inputs must be numeric'));
// }
//
// return resolve({
// value: x + y,
// x: x,
// y: y
// });
// }));
// }
//
//
// // one of the success handler
// function printResult(result) {
// console.log(result.value);
// }
//
// // another success handler
// function printResultVerbose(result) {
// console.log('(' + result.x + ',' + result.y + ') = ' + result.value);
// }
//
//
// // error handler
// function handleErrors(error) {
// console.log('Error: ' + error.message);
// }
//
//
// var p1 = addNumbers(5, 9);
// var p2 = addNumbers(25, 12);
// var p3 = addNumbers(9, 'a');
//
//
// // p1 Promise: not handling errors
// p1.then(printResult);
// p1.then(printResultVerbose);
//
// // p2 Promise: handling errors
// p2.then(printResult, handleErrors);
// p2.then(printResultVerbose, handleErrors);
//
// // p3 Promise: handling errors
// p3.then(printResult, handleErrors);
// p3.then(printResultVerbose, handleErrors);
// // Example 375 - Promise object is an instanceof Promise
// var promise = new Promise(function(resolve, reject) {});
//
// console.log(promise instanceof Promise);
// // Example 376 - Promise.race() example
// /*
// * 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.
// * */
//
// // Example from JS Docs
// var p1 = new Promise(function(resolve, reject) {
// setTimeout(resolve, 500, 'one');
// });
//
// var p2 = new Promise(function(resolve, reject) {
// setTimeout(resolve, 100, 'two');
// });
//
// Promise.race([p1, p2]).then(function(value) {
// console.log(value); // "two"
// // Both resolve, but p2 is faster
// });
// // Example 377 - Promise.race() example - even if the first completed promise is a reject()
// /*
// * 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.
// * */
//
// // Example from JS Docs
// var p1 = new Promise(function(resolve, reject) {
// setTimeout(resolve, 500, 'one');
// });
//
// var p2 = new Promise(function(resolve, reject) {
// setTimeout(reject, 100, 'two failed faster.');
// });
//
// Promise.race([p1, p2]).then(function(value) {
// console.log(value); // "two"
// }, function(error) {
// console.log(error);
// // p2 fails faster than p1 resolves
//
// });