-
Notifications
You must be signed in to change notification settings - Fork 3.8k
Expand file tree
/
Copy pathobservable-from.any.js
More file actions
1730 lines (1520 loc) · 50.6 KB
/
observable-from.any.js
File metadata and controls
1730 lines (1520 loc) · 50.6 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
// Because we test that the global error handler is called at various times.
setup({allow_uncaught_exception: true});
test(() => {
assert_equals(typeof Observable.from, "function",
"Observable.from() is a function");
}, "from(): Observable.from() is a function");
test(() => {
assert_throws_js(TypeError, () => Observable.from(10),
"Number cannot convert to an Observable");
assert_throws_js(TypeError, () => Observable.from(true),
"Boolean cannot convert to an Observable");
assert_throws_js(TypeError, () => Observable.from("String"),
"String cannot convert to an Observable");
assert_throws_js(TypeError, () => Observable.from({a: 10}),
"Object cannot convert to an Observable");
assert_throws_js(TypeError, () => Observable.from(Symbol.iterator),
"Bare Symbol.iterator cannot convert to an Observable");
assert_throws_js(TypeError, () => Observable.from(Promise),
"Promise constructor cannot convert to an Observable");
}, "from(): Failed conversions");
test(() => {
const target = new EventTarget();
const observable = target.when('custom');
const from_observable = Observable.from(observable);
assert_equals(observable, from_observable);
}, "from(): Given an observable, it returns that exact observable");
test(() => {
let completeCalled = false;
const results = [];
const array = [1, 2, 3, 'a', new Date(), 15, [12]];
const observable = Observable.from(array);
observable.subscribe({
next: v => results.push(v),
error: e => assert_unreached('error is not called'),
complete: () => completeCalled = true
});
assert_array_equals(results, array);
assert_true(completeCalled);
}, "from(): Given an array");
test(() => {
const iterable = {
[Symbol.iterator]() {
let n = 0;
return {
next() {
n++;
if (n <= 3) {
return { value: n, done: false };
}
return { value: undefined, done: true };
},
};
},
};
const observable = Observable.from(iterable);
assert_true(observable instanceof Observable, "Observable.from() returns an Observable");
const results = [];
observable.subscribe({
next: (value) => results.push(value),
error: () => assert_unreached("should not error"),
complete: () => results.push("complete"),
});
assert_array_equals(results, [1, 2, 3, "complete"],
"Subscription pushes iterable values out to Observable");
// A second subscription should restart iteration.
observable.subscribe({
next: (value) => results.push(value),
error: () => assert_unreached("should not error"),
complete: () => results.push("complete2"),
});
assert_array_equals(results, [1, 2, 3, "complete", 1, 2, 3, "complete2"],
"Subscribing again causes another fresh iteration on an un-exhausted iterable");
}, "from(): Iterable converts to Observable");
// This test, and the variants below it, test the web-observable side-effects of
// converting an iterable object to an Observable. Specifically, it tracks
// exactly when the %Symbol.iterator% method is *retrieved* from the object,
// invoked, and what its error-throwing side-effects are.
//
// Even more specifically, we assert that the %Symbol.iterator% method is
// retrieved a single time when converting to an Observable, and then again when
// subscribing to the converted Observable. This makes it possible for the
// %Symbol.iterator% method getter to change return values in between conversion
// and subscription. See https://github.com/WICG/observable/issues/127 for
// related discussion.
test(() => {
const results = [];
const iterable = {
get [Symbol.iterator]() {
results.push("[Symbol.iterator] method GETTER");
return function() {
results.push("[Symbol.iterator implementation]");
return {
get next() {
results.push("next() method GETTER");
return function() {
results.push("next() implementation");
return {value: undefined, done: true};
};
},
};
};
},
};
const observable = Observable.from(iterable);
assert_array_equals(results, ["[Symbol.iterator] method GETTER"]);
let thrownError = null;
observable.subscribe();
assert_array_equals(results, [
"[Symbol.iterator] method GETTER",
"[Symbol.iterator] method GETTER",
"[Symbol.iterator implementation]",
"next() method GETTER",
"next() implementation"
]);
}, "from(): [Symbol.iterator] side-effects (one observable)");
// This tests that once `Observable.from()` detects a non-null and non-undefined
// `[Symbol.iterator]` property, we've committed to converting as an iterable.
// If the value of that property is then not callable, we don't silently move on
// to the next conversion type — we throw a TypeError.
//
// That's because that's what TC39's `GetMethod()` [1] calls for, which is what
// `Observable.from()` first uses in the iterable conversion branch [2].
//
// [1]: https://tc39.es/ecma262/multipage/abstract-operations.html#sec-getmethod
// [2]: http://wicg.github.io/observable/#from-iterable-conversion
test(() => {
let results = [];
const iterable = {
[Symbol.iterator]: 10,
};
let errorThrown = null;
try {
Observable.from(iterable);
} catch(e) {
errorThrown = e;
}
assert_true(errorThrown instanceof TypeError);
}, "from(): [Symbol.iterator] not callable");
test(() => {
let results = [];
const iterable = {
calledOnce: false,
get [Symbol.iterator]() {
if (this.calledOnce) {
// Return a non-callable primitive the second time `@@iterator` is
// called.
return 10;
}
this.calledOnce = true;
return this.validImplementation;
},
validImplementation: () => {
return {
next() { return {done: true}; }
}
}
};
let errorThrown = null;
const observable = Observable.from(iterable);
observable.subscribe({
next: v => results.push("should not be called"),
error: e => {
errorThrown = e;
results.push(e);
},
});
assert_array_equals(results, [errorThrown],
"An error was plumbed through the Observable");
assert_true(errorThrown instanceof TypeError);
}, "from(): [Symbol.iterator] not callable AFTER SUBSCRIBE throws");
test(() => {
let results = [];
const iterable = {
calledOnce: false,
validImplementation: () => {
return {
next() { return {done: true}; }
}
},
get [Symbol.iterator]() {
if (this.calledOnce) {
// Return null the second time `@@iterator` is called.
return null;
}
this.calledOnce = true;
return this.validImplementation;
}
};
let errorThrown = null;
const observable = Observable.from(iterable);
observable.subscribe({
next: v => results.push("should not be called"),
error: e => {
errorThrown = e;
results.push(e);
},
});
assert_array_equals(results, [errorThrown],
"An error was plumbed through the Observable");
assert_true(errorThrown instanceof TypeError);
}, "from(): [Symbol.iterator] returns null AFTER SUBSCRIBE throws");
test(() => {
let results = [];
const customError = new Error("@@iterator override error");
const iterable = {
numTimesCalled: 0,
// The first time this getter is called, it returns a legitimate function
// that, when called, returns an iterator. Every other time it returns an
// error-throwing function that does not return an iterator.
get [Symbol.iterator]() {
this.numTimesCalled++;
results.push("[Symbol.iterator] method GETTER");
if (this.numTimesCalled === 1) {
return this.validIteratorImplementation;
} else {
return this.errorThrowingIteratorImplementation;
}
},
validIteratorImplementation: function() {
results.push("[Symbol.iterator implementation]");
return {
get next() {
results.push("next() method GETTER");
return function() {
results.push("next() implementation");
return {value: undefined, done: true};
}
}
};
},
errorThrowingIteratorImplementation: function() {
results.push("Error-throwing [Symbol.iterator] implementation");
throw customError;
},
};
const observable = Observable.from(iterable);
assert_array_equals(results, [
"[Symbol.iterator] method GETTER",
]);
// Override iterable's `[Symbol.iterator]` protocol with an error-throwing
// function. We assert that on subscription, this method (the new `@@iterator`
// implementation), is called because only the raw JS object gets stored in
// the Observable that results in conversion. This raw value must get
// re-converted to an iterable once iteration is about to start.
let thrownError = null;
observable.subscribe({
error: e => thrownError = e,
});
assert_equals(thrownError, customError,
"Error thrown from next() is passed to the error() handler");
assert_array_equals(results, [
// Old:
"[Symbol.iterator] method GETTER",
// New:
"[Symbol.iterator] method GETTER",
"Error-throwing [Symbol.iterator] implementation"
]);
}, "from(): [Symbol.iterator] is not cached");
// Similar to the above test, but with more Observables!
test(() => {
const results = [];
let numTimesSymbolIteratorCalled = 0;
let numTimesNextCalled = 0;
const iterable = {
get [Symbol.iterator]() {
results.push("[Symbol.iterator] method GETTER");
return this.internalIteratorImplementation;
},
set [Symbol.iterator](func) {
this.internalIteratorImplementation = func;
},
internalIteratorImplementation: function() {
results.push("[Symbol.iterator] implementation");
return {
get next() {
results.push("next() method GETTER");
return function() {
results.push("next() implementation");
return {value: undefined, done: true};
};
},
};
},
};
const obs1 = Observable.from(iterable);
const obs2 = Observable.from(iterable);
const obs3 = Observable.from(iterable);
const obs4 = Observable.from(obs3);
assert_equals(obs3, obs4);
assert_array_equals(results, [
"[Symbol.iterator] method GETTER",
"[Symbol.iterator] method GETTER",
"[Symbol.iterator] method GETTER",
]);
obs1.subscribe();
assert_array_equals(results, [
// Old:
"[Symbol.iterator] method GETTER",
"[Symbol.iterator] method GETTER",
"[Symbol.iterator] method GETTER",
// New:
"[Symbol.iterator] method GETTER",
"[Symbol.iterator] implementation",
"next() method GETTER",
"next() implementation",
]);
iterable[Symbol.iterator] = () => {
results.push("Error-throwing [Symbol.iterator] implementation");
throw new Error('Symbol.iterator override error');
};
let errorCount = 0;
const observer = {error: e => errorCount++};
obs2.subscribe(observer);
obs3.subscribe(observer);
obs4.subscribe(observer);
assert_equals(errorCount, 3,
"Error-throwing `@@iterator` implementation is called once per " +
"subscription");
assert_array_equals(results, [
// Old:
"[Symbol.iterator] method GETTER",
"[Symbol.iterator] method GETTER",
"[Symbol.iterator] method GETTER",
"[Symbol.iterator] method GETTER",
"[Symbol.iterator] implementation",
"next() method GETTER",
"next() implementation",
// New:
"[Symbol.iterator] method GETTER",
"Error-throwing [Symbol.iterator] implementation",
"[Symbol.iterator] method GETTER",
"Error-throwing [Symbol.iterator] implementation",
"[Symbol.iterator] method GETTER",
"Error-throwing [Symbol.iterator] implementation",
]);
}, "from(): [Symbol.iterator] side-effects (many observables)");
test(() => {
const customError = new Error('@@iterator next() error');
const iterable = {
[Symbol.iterator]() {
return {
next() {
throw customError;
}
};
}
};
let thrownError = null;
Observable.from(iterable).subscribe({
error: e => thrownError = e,
});
assert_equals(thrownError, customError,
"Error thrown from next() is passed to the error() handler");
}, "from(): [Symbol.iterator] next() throws error");
promise_test(async () => {
const promise = Promise.resolve('value');
const observable = Observable.from(promise);
assert_true(observable instanceof Observable, "Converts to Observable");
const results = [];
observable.subscribe({
next: (value) => results.push(value),
error: () => assert_unreached("error() is not called"),
complete: () => results.push("complete()"),
});
assert_array_equals(results, [], "Observable does not emit synchronously");
await promise;
assert_array_equals(results, ["value", "complete()"],
"Observable emits and completes after Promise resolves");
}, "from(): Converts Promise to Observable");
promise_test(async t => {
let unhandledRejectionHandlerCalled = false;
const unhandledRejectionHandler = () => {
unhandledRejectionHandlerCalled = true;
};
self.addEventListener("unhandledrejection", unhandledRejectionHandler);
t.add_cleanup(() => self.removeEventListener("unhandledrejection", unhandledRejectionHandler));
const promise = Promise.reject("reason");
const observable = Observable.from(promise);
assert_true(observable instanceof Observable, "Converts to Observable");
const results = [];
observable.subscribe({
next: (value) => assert_unreached("next() not called"),
error: (error) => results.push(error),
complete: () => assert_unreached("complete() not called"),
});
assert_array_equals(results, [], "Observable does not emit synchronously");
let catchBlockEntered = false;
try {
await promise;
} catch {
catchBlockEntered = true;
}
assert_true(catchBlockEntered, "Catch block entered");
assert_false(unhandledRejectionHandlerCalled, "No unhandledrejection event");
assert_array_equals(results, ["reason"],
"Observable emits error() after Promise rejects");
}, "from(): Converts rejected Promise to Observable. No " +
"`unhandledrejection` event when error is handled by subscription");
promise_test(async t => {
let unhandledRejectionHandlerCalled = false;
const unhandledRejectionHandler = () => {
unhandledRejectionHandlerCalled = true;
};
self.addEventListener("unhandledrejection", unhandledRejectionHandler);
t.add_cleanup(() => self.removeEventListener("unhandledrejection", unhandledRejectionHandler));
let errorReported = null;
self.addEventListener("error", e => errorReported = e, { once: true });
let catchBlockEntered = false;
try {
const promise = Promise.reject("custom reason");
const observable = Observable.from(promise);
observable.subscribe();
await promise;
} catch {
catchBlockEntered = true;
}
assert_true(catchBlockEntered, "Catch block entered");
assert_false(unhandledRejectionHandlerCalled,
"No unhandledrejection event, because error got reported to global");
assert_not_equals(errorReported, null, "Error was reported to the global");
assert_true(errorReported.message.includes("custom reason"),
"Error message matches");
assert_equals(errorReported.lineno, 0, "Error lineno is 0");
assert_equals(errorReported.colno, 0, "Error lineno is 0");
assert_equals(errorReported.error, "custom reason",
"Error object is equivalent");
}, "from(): Rejections not handled by subscription are reported to the " +
"global, and still not sent as an unhandledrejection event");
test(() => {
const results = [];
const observable = new Observable(subscriber => {
subscriber.next('from Observable');
subscriber.complete();
});
observable[Symbol.iterator] = () => {
results.push('Symbol.iterator() called');
return {
next() {
return {value: 'from @@iterator', done: true};
}
};
};
Observable.from(observable).subscribe({
next: v => results.push(v),
complete: () => results.push("complete"),
});
assert_array_equals(results, ["from Observable", "complete"]);
}, "from(): Observable that implements @@iterator protocol gets converted " +
"as an Observable, not iterator");
test(() => {
const results = [];
const promise = new Promise(resolve => {
resolve('from Promise');
});
promise[Symbol.iterator] = () => {
let done = false;
return {
next() {
if (!done) {
done = true;
return {value: 'from @@iterator', done: false};
} else {
return {value: undefined, done: true};
}
}
};
};
Observable.from(promise).subscribe({
next: v => results.push(v),
complete: () => results.push("complete"),
});
assert_array_equals(results, ["from @@iterator", "complete"]);
}, "from(): Promise that implements @@iterator protocol gets converted as " +
"an iterable, not Promise");
// When the [Symbol.iterator] method on a given object is undefined, we don't
// try to convert the object to an Observable via the iterable protocol. The
// Observable specification *also* does the same thing if the [Symbol.iterator]
// method is *null*. That is, in that case we also skip the conversion via
// iterable protocol, and continue to try and convert the object as another type
// (in this case, a Promise).
promise_test(async () => {
const promise = new Promise(resolve => resolve('from Promise'));
assert_equals(promise[Symbol.iterator], undefined);
promise[Symbol.iterator] = null;
assert_equals(promise[Symbol.iterator], null);
const value = await new Promise(resolve => {
Observable.from(promise).subscribe(value => resolve(value));
});
assert_equals(value, 'from Promise');
}, "from(): Promise whose [Symbol.iterator] returns null converts as Promise");
// This is a more sensitive test, which asserts that even just trying to reach
// for the [Symbol.iterator] method on an object whose *getter* for the
// [Symbol.iterator] method throws an error, results in `Observable#from()`
// rethrowing that error.
test(() => {
const error = new Error('thrown from @@iterator getter');
const obj = {
get [Symbol.iterator]() {
throw error;
}
}
try {
Observable.from(obj);
assert_unreached("from() conversion throws");
} catch(e) {
assert_equals(e, error);
}
}, "from(): Rethrows the error when Converting an object whose @@iterator " +
"method *getter* throws an error");
// This test exercises the line of spec prose that says:
//
// "If |asyncIteratorMethodRecord|'s [[Value]] is undefined or null, then jump
// to the step labeled 'From iterable'."
test(() => {
const sync_iterable = {
[Symbol.asyncIterator]: null,
[Symbol.iterator]() {
return {
value: 0,
next() {
if (this.value === 2)
return {value: undefined, done: true};
else
return {value: this.value++, done: false};
}
}
},
};
const results = [];
const source = Observable.from(sync_iterable).subscribe(v => results.push(v));
assert_array_equals(results, [0, 1]);
}, "from(): Async iterable protocol null, converts as iterator");
promise_test(async t => {
const results = [];
const async_iterable = {
[Symbol.asyncIterator]() {
results.push("[Symbol.asyncIterator]() invoked");
return {
val: 0,
next() {
return new Promise(resolve => {
t.step_timeout(() => {
resolve({
value: this.val,
done: this.val++ === 4 ? true : false,
});
}, 400);
});
},
};
},
};
const source = Observable.from(async_iterable);
assert_array_equals(results, []);
await new Promise(resolve => {
source.subscribe({
next: v => {
results.push(`Observing ${v}`);
queueMicrotask(() => results.push(`next() microtask interleaving (v=${v})`));
},
complete: () => {
results.push('complete()');
resolve();
},
});
});
assert_array_equals(results, [
"[Symbol.asyncIterator]() invoked",
"Observing 0",
"next() microtask interleaving (v=0)",
"Observing 1",
"next() microtask interleaving (v=1)",
"Observing 2",
"next() microtask interleaving (v=2)",
"Observing 3",
"next() microtask interleaving (v=3)",
"complete()",
]);
}, "from(): Asynchronous iterable conversion");
// This test is a more chaotic version of the above. It ensures that a single
// Observable can handle multiple in-flight subscriptions to the same underlying
// async iterable without the two subscriptions competing. It asserts that the
// asynchronous values are pushed to the observers in the correct order.
promise_test(async t => {
const async_iterable = {
[Symbol.asyncIterator]() {
return {
val: 0,
next() {
// Returns a Promise that resolves in a random amount of time less
// than a second.
return new Promise(resolve => {
t.step_timeout(() => resolve({
value: this.val,
done: this.val++ === 4 ? true : false,
}), 200);
});
},
};
},
};
const results = [];
const source = Observable.from(async_iterable);
const promise = new Promise(resolve => {
source.subscribe({
next: v => {
results.push(`${v}-first-sub`);
// Half-way through the first subscription, start another subscription.
if (v === 0) {
source.subscribe({
next: v => results.push(`${v}-second-sub`),
complete: () => {
results.push('complete-second-sub');
resolve();
}
});
}
},
complete: () => {
results.push('complete-first-sub');
resolve();
}
});
});
await promise;
assert_array_equals(results, [
'0-first-sub',
'1-first-sub',
'1-second-sub',
'2-first-sub',
'2-second-sub',
'3-first-sub',
'3-second-sub',
'complete-first-sub',
'complete-second-sub',
]);
}, "from(): Asynchronous iterable multiple in-flight subscriptions");
// This test is like the above, ensuring that multiple subscriptions to the same
// sync-iterable-converted-Observable can exist at a time. Since sync iterables
// push all of their values to the Observable synchronously, the way to do this
// is subscribe to the sync iterable Observable *inside* the next handler of the
// same Observable.
test(() => {
const results = [];
const array = [1, 2, 3, 4, 5];
const source = Observable.from(array);
source.subscribe({
next: v => {
results.push(`${v}-first-sub`);
if (v === 3) {
// Pushes all 5 values to `results` right after the first instance of `3`.
source.subscribe({
next: v => results.push(`${v}-second-sub`),
complete: () => results.push('complete-second-sub'),
});
}
},
complete: () => results.push('complete-first-sub'),
});
assert_array_equals(results, [
// These values are pushed when there is only a single subscription.
'1-first-sub', '2-first-sub', '3-first-sub',
// These values are pushed in the correct order, for two subscriptions.
'4-first-sub', '4-second-sub',
'5-first-sub', '5-second-sub',
'complete-first-sub', 'complete-second-sub',
]);
}, "from(): Sync iterable multiple in-flight subscriptions");
promise_test(async () => {
const async_generator = async function*() {
yield 1;
yield 2;
yield 3;
};
const results = [];
const source = Observable.from(async_generator());
const subscribeFunction = function(resolve) {
source.subscribe({
next: v => results.push(v),
complete: () => resolve(),
});
}
await new Promise(subscribeFunction);
assert_array_equals(results, [1, 2, 3]);
await new Promise(subscribeFunction);
assert_array_equals(results, [1, 2, 3]);
}, "from(): Asynchronous generator conversion: can only be used once");
// The value returned by an async iterator object's `next()` method is supposed
// to be a Promise. But this requirement "isn't enforced": see [1]. Therefore,
// the Observable spec unconditionally wraps the return value in a resolved
// Promise, as is standard practice [2].
//
// This test ensures that even if the object returned from an async iterator's
// `next()` method is a synchronously-available object with `done: true`
// (instead of a Promise), the `done` property is STILL not retrieved
// synchronously. In other words, we test that the Promise-wrapping is
// implemented.
//
// [1]: https://tc39.es/ecma262/#table-async-iterator-r
// [2]: https://matrixlogs.bakkot.com/WHATWG/2024-08-30#L30
promise_test(async () => {
const results = [];
const async_iterable = {
[Symbol.asyncIterator]() {
return {
next() {
return {
value: undefined,
get done() {
results.push('done() GETTER called');
return true;
},
};
},
};
},
};
const source = Observable.from(async_iterable);
assert_array_equals(results, []);
queueMicrotask(() => results.push('Microtask queued before subscription'));
source.subscribe();
assert_array_equals(results, []);
await Promise.resolve();
assert_array_equals(results, [
"Microtask queued before subscription",
"done() GETTER called",
]);
}, "from(): Promise-wrapping semantics of IteratorResult interface");
// Errors thrown from [Symbol.asyncIterator] are propagated to the observer
// synchronously. This is because in language constructs (i.e., for-await of
// loops) that invoke [Symbol.asyncIterator]() that throw errors, the errors are
// synchronously propagated to script outside of the loop, and are catchable.
// Observables follow this precedent.
test(() => {
const error = new Error("[Symbol.asyncIterator] error");
const results = [];
const async_iterable = {
[Symbol.asyncIterator]() {
results.push("[Symbol.asyncIterator]() invoked");
throw error;
}
};
Observable.from(async_iterable).subscribe({
error: e => results.push(e),
});
assert_array_equals(results, [
"[Symbol.asyncIterator]() invoked",
error,
]);
}, "from(): Errors thrown in Symbol.asyncIterator() are propagated synchronously");
// AsyncIterable: next() throws exception instead of return Promise. Any errors
// that occur during the the retrieval of `next()` always result in a rejected
// Promise. Therefore, the error makes it to the Observer with microtask timing.
promise_test(async () => {
const nextError = new Error('next error');
const async_iterable = {
[Symbol.asyncIterator]() {
return {
get next() {
throw nextError;
}
};
}
};
const results = [];
Observable.from(async_iterable).subscribe({
error: e => results.push(e),
});
assert_array_equals(results, []);
// Wait one microtask since the error will be propagated through a rejected
// Promise managed by the async iterable conversion semantics.
await Promise.resolve();
assert_array_equals(results, [nextError]);
}, "from(): Errors thrown in async iterator's next() GETTER are propagated " +
"in a microtask");
promise_test(async () => {
const nextError = new Error('next error');
const async_iterable = {
[Symbol.asyncIterator]() {
return {
next() {
throw nextError;
}
};
}
};
const results = [];
Observable.from(async_iterable).subscribe({
error: e => results.push(e),
});
assert_array_equals(results, []);
await Promise.resolve();
assert_array_equals(results, [nextError]);
}, "from(): Errors thrown in async iterator's next() are propagated in a microtask");
test(() => {
const results = [];
const iterable = {
[Symbol.iterator]() {
return {
val: 0,
next() {
results.push(`IteratorRecord#next() pushing ${this.val}`);
return {
value: this.val,
done: this.val++ === 10 ? true : false,
};
},
return() {
results.push(`IteratorRecord#return() called with this.val=${this.val}`);
},
};
},
};
const ac = new AbortController();
Observable.from(iterable).subscribe(v => {
results.push(`Observing ${v}`);
if (v === 3) {
ac.abort();
}
}, {signal: ac.signal});
assert_array_equals(results, [
"IteratorRecord#next() pushing 0",
"Observing 0",
"IteratorRecord#next() pushing 1",
"Observing 1",
"IteratorRecord#next() pushing 2",
"Observing 2",
"IteratorRecord#next() pushing 3",
"Observing 3",
"IteratorRecord#return() called with this.val=4",
]);
}, "from(): Aborting sync iterable midway through iteration both stops iteration " +
"and invokes `IteratorRecord#return()");
// Like the above test, but for async iterables.
promise_test(async t => {
const results = [];
const iterable = {
[Symbol.asyncIterator]() {
return {
val: 0,
next() {
results.push(`IteratorRecord#next() pushing ${this.val}`);
return {
value: this.val,
done: this.val++ === 10 ? true : false,
};
},
return(reason) {
results.push(`IteratorRecord#return() called with reason=${reason}`);
return {done: true};
},
};
},
};
const ac = new AbortController();
await new Promise(resolve => {
Observable.from(iterable).subscribe(v => {
results.push(`Observing ${v}`);
if (v === 3) {
ac.abort(`Aborting because v=${v}`);
resolve();
}
}, {signal: ac.signal});
});
assert_array_equals(results, [
"IteratorRecord#next() pushing 0",
"Observing 0",
"IteratorRecord#next() pushing 1",
"Observing 1",
"IteratorRecord#next() pushing 2",
"Observing 2",
"IteratorRecord#next() pushing 3",
"Observing 3",
"IteratorRecord#return() called with reason=Aborting because v=3",