-
Notifications
You must be signed in to change notification settings - Fork 112
/
Copy pathjul-28.md
1250 lines (698 loc) · 37.9 KB
/
jul-28.md
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
# July 28, 2016 Meeting Notes
-----
Brian Terlson (BT), Michael Ficarra (MF), Jordan Harband (JHD), Waldemar Horwat (WH), Tim Disney (TD), Michael Saboff (phone) (MLS), Chip Morningstar (CM), Daniel Ehrenberg (DE), Leo Balter (LEO), Yehuda Katz (YK), Jafar Husain (JH), István Sebestyén (IS), John Neumann (JN), Domenic Denicola (DD), Rick Waldron (RW), Stefan Penner (SP), Jonathan Sampson (JSN), Caridy Patiño (CP), Sam Tobin-Hochstadt (STH), John Buchanan (JB), Kevin Gibbons (KG), Lars Hansen (LHN), Tom Care (TC), Dave Herman (DH), Bradley Farias (BFS), Kris Gray (KGY), Adam Klein (AK), Dean Tribble (DT), Eric Faust (EFT), Jeff Morrison (JM), Sebastian Markbåge (SM), Saam Barati (SBI), Kris Gray (KGY), John-David Dalton (JDD), Ben Newman (BN), Morgan Phillips (MPS), Shu-yu Guo (SYG), Paul Leathers (PL), Ben Smith (BS), Zibi Braniecki (ZB)
-----
## 10.ii.a Shared Memory And Atomics
Lars Hansen
https://github.com/tc39/ecmascript_sharedmem
LHN:
### Agent Semantics
Blocking: an agent can block waiting to be woken without returning to its event loop
Web awareness: an embedding can deny some agents the ability to block (eg. browsers main thread)
Forward progress: agents must eventually advance if
All agents die at the same time
### SharedArrayBuffer
- New Data Type
- Like ArrayBuffer
- map TypedArray and DataView onto it
- Unlike (see slide)
Sharing Memory
### `Atomics`
The global `Atomics` namespace has static methods that operate on TypedArrays
Atomic access:
- `load`
- `store`
- `add`
- `sub`
- `and`
- `or`
- `xor`
- `exchange`
- `compareExchange`
BFS: Is it possible to have another worker store between wake?
EFT: Yes
DT: A spin instruction that doesn't spin, on x86?
LHN: Yes
- Investigated `pause` as a lightweight `wait`, that wouldn't go into a spin, but `wait` for a short time
- if hot `wait`, could've used `pause` before going into a `wait`
- you could use `pause` instead of direct into `wait`
(I'm not sure I captured this as well as it could be, would appreciate more eyes/brains to revise appropriately)
### Memory Model
... see slide
### Challenges
... see slide
### Opportunities
ES is "easier" than C/C++
- Performance demands slightly lower
- Shared Memory sep. from non-shared
- Only flat shared memory, no pointers or objects
... see slide
### Two Level memory model 1
Conventional axiomatic high level model
- Defines sync accesses
- sync order
- "happens=before" relationship
... see slide
### Two Level memory model 2
... see slide
### Synchronization Order
... see slide
### Viability 1
... see slide
### Viability 2
... see slide
LHN: WH found an important bug in the memory model's definition of viability that causes the synchronization order to not be well-defined. Without a well-defined synchronization order we don't have a workable model. This will require a rewrite using an operational approach instead of the current two-phase viability and synchronization approach.
LHN: [talking about slide] Races "leaking" into the memory model of the sequential language.
WH: Agree that they don't leak (and must not leak). The price we pay for that is significant loss of opportunities for optimizations. It remains to be seen whether that's a reasonable price, but I assume it is for now for the purposes of this proposal.
LHN: [talking about slide] Security issues are the "cost of doing business" of shipping shared memory, at least according to one major browser vendor. Mozilla is less sanguine about that.
MM: Is there any way to ameliorate this?
LHN: Add a switch to settings to turn multithreading off.
(discussion, re: changes that need to be made)
WH: The memory model will need to be rewritten.
?: Why rewrite? Can't we just fix the bugs that WH found in the presented memory model?
LHN: What I just presented is the new memory model I'm developing to fix the bugs, not the one currently in the spec.
- Avoid a circular
WH: What was in the spec had fundamental incorrect assumptions such as defining viability as a separate phase before synchronization, or the ability to put all memory accesses (including non-atomic ones) into a global total order, which just isn't true.
WH: We all agree on what the simple cases where everything is synchronized properly ought to do, such as what happens in an atomic load that sees the result of a prior atomic store. It's in the other cases that need to be nailed down where the big memory model issues lie.
SYG: How to test?
- An impl to be compliant, must be able to observe the memory model
- Is that possible?
BS: without particular axiom, here is X that breaks.
SYG:
STH: Write the memory model, rep. all the legal executions. Run X times, ensure that all
SYG: How to test the actual implementation
#### Conclusion/Resolution
- Stage 3 acceptance
- After Waldemar is satisfied with rewrite of memory model
- API freeze granted?
## 10.i.b Disregard lastIndex for non-global non-sticky regexps
(Leo Balter)
PR from Claude Pache https://github.com/tc39/ecma262/pull/627
LEO: The change is: "don't do the lastIndex step unless isn't actually necessary"
https://github.com/tc39/ecma262/issues/625
DE: Global regexps don't make sense when frozen
- Some programs freeze regexps, unsure why.
- This is in use, received bug reports
(discussion, re: how long this might've been allowed?)
AWB: user-freezable properties and strict mode introduced in ES5
DE: Doesn't make sense to read/write lastIndex unless actually necessary.
AWB: Could break something
DE: True
- The plan is to attempt the fix, ship on chrome/canary and see what happens
AWB: (recapping the proposed fix)
LEO: This PR also adds a change to avoid get and ToLength operations on lastIndex for the same regexps. A poisoned RegExp lastIndex property wouldn't affect it.
```js
function test(rx) {
rx.lastIndex = { valueOf: function () { throw "ok" } }
try {
rx.exec('foo')
}
catch (e) {
if (e === "ok")
return true
}
return false
}
```
LEO: After this patch, a `test(/a/)` should return false.
MM: That does not only address the web compatibility issue, but does a clean-up on the lastIndex.
#### Conclusion/Resolution
- Merge it
- Implement in canary and report what happens
## 10.iii.d Object.shallowEqual
(Sebastian Markbåge)
- [proposal](https://github.com/sebmarkbage/ecmascript-shallow-equal)
SBI: Problem...
### Memoization
... see slide
```js
function eq(a, b) {
return Object.is(a, b);
}
function memoize(fn) {
let lastArg, lastResult;
return function(arg) {
if (lastArg !== undefined && eq(lastArg, arg)) {
return lastResult;
}
lastArg = arg;
lastResult = fn(arg);
return lastResult;
};
}
function calc(obj) {
return obj.x + obj.y;
}
let memoizedCalc = memoize(calc);
let obj = { x: 1, y: 2 };
let res1 = memoizedCalc(obj); // slow
let res2 = memoizedCalc(obj); // quick
let res3 = memoizedCalc({ x: 3, y: 4 }); // slow
```
SM: Would like to be able to compare only the own property values
WH/MM: (discussion about concerns and objections that have been previously discussed)
YK: Does this anticipate being faster on value types?
WH: As an evil villain I love the ability this might give me to compare the internal variables captured inside closures [scary emoji]. Mwa ha ha ha ha!
MM: That's one of the issues I had raised.
YK: ?
SM: Most of the time, returns false.
YK: (equating semantics to memcmp)
AK: No, memcmp is just implementation suggestion
MM: The semantics:
- If the answer is true, guarantees follow
- If returns false, no guarantees follow
YK: The guarantee using Object.is?
MM: Uses identity
SM: Compare objects across realms is also a question
YK: Ok, the intended implementation is memcmp
(confirm)
FST: There's a browser war on. If [browser x] returns true 30% of the time in this case, then I must return true at least 25% of the time.
AWB: Are there other approaches you could use to obtain much better performance?
YK: The whole thing is a performance detail which we don't really specify. There are some things that look like value types but in fact have expensive === operations.
AWB: We chose to have multiple representations of things like strings for performance reasons. Now they will cost us. It's hard to specify semantics.
FST: As a browser vendor I don't want to constrain otherwise efficient representations due to the performance implications of wanting to return true from this feature.
MM: This is affected by the transposed implementation of weak maps.
WH: And it leaks information about what's in the weak map.
MM: You'd want closure state to not be part of the comparison.
MM: We want to store private state in object slots, but we want object scans to not reveal anything about the private state.
FST: Implementations will need to distinguish different kinds of internal slots anyway.
WH: This presents similar issues to NaN comparison, but for strings. As the example in the presentation showed, now you can figure out the pedigree of whether a string was constructed in one piece or as a rope by something on the other side of an abstraction boundary — something that must not be leaked for security reasons.
BE: leaking string implementation details (Rope vs. Flat representation) has been constructive for Heartbleed-like security attacks in past.
STH: evidence of the code you've written being slow enough
SM: no evidence yet
AWB: Here's another path... bring the slow path code to implementors and try to optimize in the runtime. Then with this experience, determine a proposal for language or built-in library changes
SM: Will try
WH: Do implementations ever store hashes along with strings to be able to quickly determine that they are not equal?
FST: We intern some strings, but not all.
(discussion, re: hashing, string interning)
YK: MM, are you not worried about the moving GC leak?
MM: I am.
YK: Moving GC... do a comparison, it's true. The object is changed by GC, and becomes false
STH: No
EFT: If there is a concrete case that shows instability, we can explore
WH: Can discover if implementations do lazy string interning
MM: Do meet S1 criteria, but not worth trying to move this forward because this doesn't have a chance of advancing further. Identified real issues, that we can find a way to address. Sam's suggestion might be the only viable
STH: Actual shallow comparison, implement that in VM and work on optimizing.
AWB: Essentially same as my suggestion
Agreement, but comments from implementors that I didn't quite catch
SM: Object.assign could be done much faster in VM, WeakRefs... Plausible to find other ways to accomplish same thing. Difficult to reach non-leaking solution.
MM:
Something about exploring alternative solutions
It's hard to hear because they are across the room and basically mumbling as far as I can tell. Mark is facing away and it sounds like "mmph mm-mmmph err mmph foo sh mmph sh"
(discussing "fast")
YK: VM authors recognize security issue of fast
MM: How much slower would be an accurate implementation of shallow comparison be?
SM: Would it be possible to expose the ability to compare shapes [or use the shape as a key in a map]?
MM: The nondeterminism arguments apply to anything that assumes same shape.
#### Conclusion/Resolution
- Explore STH/AWB recommendations
## 10.iii.b Promise.prototype.finally
Jordan Harband
https://github.com/ljharb/proposal-promise-finally
JHD: (presenting from the link above)
AWB: How would a user write something that is rejected from a finalizer?
WH: What does finally return?
JHD: A new promise
DD: Conceptually wrong to overwrite return values
YK: There is control flow model and have way to...
WH: How does this interact with thenables?
JHD: If the finally return value is a thenable that's resolved normally then it gets replaced with the prior resolved value.
WH: Does this introduce a notion of finally-able with parts of the system probing for the presence of a "finally" method analogous to what they do with probing for a "then" method?
MM/JHD: No, just like we don't have a "catchable"
JHD: (explanation of naming, can be reviewed in proposal)
BE: names are metaphorical and analogical, not only identical up to isomorphism; finally seems good to me.
- Existing implementations noted as well
MM: Some "wrinkle" in Q?
JHD: Will identify and note if necessary
DD: Could be naming, ie. "fin" for ES3?
BE: `promise['finally'](...)`
JHD: No conflict re: cancelable promises proposal
YK: Might be good to have finally in language, before 3rd state
JHD: Same
- Devs can proactively use finally where semantics match
YK: Might be hard to convince that finally is the right thing to do
AWB: Why wasn't finally included in ES6?
YK/MM: The ES6 Promise feature was "maximally minimal", so finally, along with others, eg. queue, were postponed
JHD: Stage 1? Note that this meets the Stage 2 requirements.
JHD: Stage 2?
DD/DE: There are issues that need to be addressed in this spec text
JHD: changes needed in this spec, to reach Stage 3
- PromiseReactionJob needs attention
MM: Want to revert my Stage 2 agreement...?
JHD: (cites Stage 2 from process doc)
MM: (something about Stages)
JHD: If I get Stage 2 now, I can work towards Stage 3 in September
(General discussion about process)
YK: We frequently have disagreements about the process.
DD: Disagreements on process aren't helpful
AWB: Don't want to jump feature two stages in one meeting
YK: The criteria is met
- I want criteria that's objectively applicable
AK: The criteria is "there is spec text to review"
JHD: Since this was on the agenda for May, then everyone diligently reviewed, right?
AK: There is no review requirement on Stage 2 spec text. Achieving Stage 3 requires review and revision, etc.
JHD: So, AWB objects to Stage 2 on the grounds that it's two stages in one meeting.
AWB: Won't block if the rest of the room wants to advance
WH: Have no objection to this, but in the future I'd love a prior notice on the agenda for any item that wants to jump more than one stage so I can look at it much more carefully before the meeting.
#### Conclusion/Resolution
- Stage 1 acceptance
- Stage 2 acceptance
## 10.iv.b Cancelable promises update
Domenic Denicola
Slides: https://docs.google.com/presentation/d/1kSY7X1ymw5f2oatDrZaMJh4Z_wpd0ynZIimhUyqhbrY/edit#slide=id.g15f86355f5_0_55
DD: Major change: third state
- A new completion type is unable to achieve consensus
- Concern:
```js
try {
f();
g();
} catch (e) {
h();
}
```
A new exception that is not an error: Cancel
- Does not subclass Error
- Branded with a [[CancelBrand]] internal slot
- Does not get reported to the host
- window.onerror
- process.on("uncaughtException", ...)
- Does not get tracked as an unhandled rejection either
- throw Cancel("message")
Making it easy to treat cancelations as non-errors
Bad code...
```js
try {
await fetch(...);
} catch (e) {
if (!(e instanceof CancelError)) {
showUserMessage("No data for you, sorry.");
}
} finally {
stopLoadingSpinner();
}
```
Proposal:
```js
try {
await fetch(...);
} else (e) {
showUserMessage("No data for you, sorry.");
} finally {
stopLoadingSpinner();
}
// Also, Promise.prototype.else
```
Addresses the new code, old code issue, because no old code will have this form,
JHD: (question about brand checks)
WH: Can you do try/catch/else?
DD: No
JHD: Any catch cancel?
DD: No, this is everything _but_
Cancel token's cancel() always creates a Cancel
```js
const { token, cancel } = CancelToken.source();
cancel("message");
// internally does: new Cancel("message") and stores
token.throwIfRequested(); // throws the stored Cancel
token.promise.then(value => {
// value is the stored Cancel
});
```
MM: Then still invokes the second callback?
DD: Always has been
- source of bugs
- throws happen, people expect their catch handler to be called
MM: I disagree with your opinion on the usefulness of `.then`'s second argument
DD: it's more of a power user feature.
DE: This works better with the two argument `then`. previously there was a back compat concern (with third state), and with this proposal, it's more compatible with 2-arg then.
MM: Having `else` in relation to `then`..,
Cut off by other members who are time constrained
BE: Is dependent on state of the stack?
DD: No
DE: Sounds like this is analogous to then/else, letting cancels propagate, where 'then' handles the next try and 'else' captures the non-cancel reject; I think this is consistent with the two-argument form
DT: A wants to suppress errors if A is being canceled, regardless of what B does. If B errors, it goes up to A and A can decide what to do.
DD: I recall this concern, I disagree that this matches all reality
DT: Back to try/else. Q: try this thing and my local token is canceling, suppress error, otherwise...
- Need
MM: The test: is it a cancelation?
DT: A cancelation is a fine way to implement shut down
- Need to allow the shutdown, avoid thrashing
DD: Experience shows that it's important to suppress the...
DE: Sounds like the disagreement between Dean and Domenic is whether to just suppress the one cancelation, right?
MM: Asking for: source of information is a distinct thing, expanding the syntax taking into account the token as a source of information.
DT: I'm saying we can get a syntactic form that can do both
DD: I'm only trying to address this problem,
DT: (describing example of cancelation where a download was stopped, but results in a parse error of the incompletely downloaded contents)
YK: hard to imagine a library creating a cancel token... (I missed the entire scenario, Dean started talking)
DT: I create a file and a cancel token and hand the file to the parser, then trigger the cancel token, which stops the parser. For example, stopping a page
DD: Stopping a page is a bigger deal
BE: (asking for summary of what needs to actually be addressed)
DD: The question is, is there an unobtrusive way to have syntax that provides the semantics that Dean wants?
DT: The Question: The indirect cancelation, does it turn into an error?
DD: Don't think we need to address the case of "buggy code"
- Part of why no longer championing try/catch/else
DD: The concern is about calling into a library which, you cancel the library's overall operation, and it gives you an error rather than a cancelation. The conclusion is that that is very hard for the library to do; these syntactic affordances make it hard to do as you'd have to do a catch, followed by a brand check, which is intentionally hard.
DD: I'd like the committee's feedback on the full spec, which is now much smaller due to fewer modifications to promises, etc.
DD: Some more ideas on making Promsies more ergonomic: Make cancelation easy in async functions.
More Ideas...
- Inserting cancelation opportunities into async functions
Simplest case, pass the token:
```js
async function cancelMe(cancelToken) {
doSyncThing();
await doAsyncThing(cancelToken);
await anotherOne(cancelToken);
}
```
What about uncancelable things?
With the current proposal...
```js
async function cancelMe(cancelToken) {
doSyncThing();
cancelToken.throwIfRequested();
await doAsyncUncancelableThing();
cancelToken.throwIfRequested();
await anotherOne();
}
```
Probably want...
```js
async function cancelMe(cancelToken) {
doSyncThing();
await Promise.race([
doAsyncUncancelableThing(),
cancelToken.promise.then(c => { throw c; })
]);
await Promise.race([
anotherOne(),
cancelToken.promise.then(c => { throw c; })
]);
}
```
...But that's gross.
This is better:
```js
async function cancelMe(cancelToken) {
await.cancelToken = cancelToken;
doSyncThing();
await doAsyncUncancelableThing();
await anotherOne();
}
```
Defines a new meta property:
```
await.cancelToken
```
MM: Which awaits does that change?
DD: The ones afterward?
DP: How do you get rid of it in that execution?
DD: Set to `null`
SP: An await inside an arrow function?
- Carry over?
DD: Syntax error
DT: Do uncancelable thing might be multi-turn, the only reason for race is you might want to do the stuff after as a result of cancelation
(I need that double checked, I don't think I got it correctly)
(We're looking at...)
```js
async function cancelMe(cancelToken) {
doSyncThing();
await Promise.race([
doAsyncUncancelableThing(),
cancelToken.promise.then(c => { throw c; })
]);
await Promise.race([
anotherOne(),
cancelToken.promise.then(c => { throw c; })
]);
}
```
DT: Moves final behavior from the end, to middle
DD:
DT: The conse. not obvious, not possible to test, is the "re-ordering"
DD: Not reordering
DT: it's fundamental reordering. You're moving something that is syntactically ordered, to execute out of order
YK: When async thing, await means "some promise". await.cancelToken is a new promise.
EFT: (confirm)
YK: Arrow functions do not inherit await.cancelToken because they do not generally inherit control-flow (like return) and async/await is control-flow
...
SP: There is a potential memory leak to discuss.
DD: Can we defer that?
SP: Yes.
(discussion, re: es-discuss request for changes to this proposal)
SP: Scope of cancel? Race and All
DD: coming...
(next)
With the proposal as it is:
```js
function delay(ms, cancelToken) {
return new Promise((resolve, reject, cancel) => {
const id = setTimeout(resolve, ms);
if (!cancelToken) return;
cancelToken.promise.then(cancelation => {
cancel(cancelation);
clearTimeout(id);
});
});
}
```
JHD: Would have to pass cancelation through that cancel function?
DD: Yes
Similar for XHR...
```js
function xhrAdapted(url, { cancelToken } = {}) {
return new Promise((resolve, reject, cancel) => {
const xhr = new XMLHttpRequest();
xhr.addEventListener("load", () => resolve(xhr.responseText));
xhr.addEventListener("error", () => reject(new Error("could not XHR")));
if (!cancelToken) return;
cancelToken.promise.then(cancelation => {
cancel(cancelation);
xhr.abort();
});
});
}
```
DD: Note using `new Promise` which really only used when your doing async that doesn't use promises
New API:
```js
function delay(ms, cancelToken) {
return Promise.cancelable(cancelToken, resolve => {
const id = setTimeout(resolve, ms);
return () => clearTimeout(id);
});
}
```
SP: want to make async function cancelable...?
DD: Still use promise constr with legacy code that doesn't use promises
DT: question about [token].promise.then...?
DD: Come back to it.
Cancel Token Composition?
Precedent from .NET:
`const { token, cancel } = CancelToken.linked([ct1, ct2, ...]);`
Here token is canceled if any of the following is true:
cancel() is called
ct1 becomes canceled
ct2 becomes canceled
...
I haven't really investigated what this is used for in the .NET ecosystem...
The extra cancel() seems useless and an artifact of the .NET setup, so instead:
.NET's version but a little better
`const token = CancelToken.some([ct1, ct2, ...]);`
Here token is canceled if any of the following is true:
ct1 becomes canceled
ct2 becomes canceled
...
Still unsure what the exact use cases are, but it seems plausible.
DD: Call it "some" or "any"
SP: The leak: scenario where cancel token is much longer lived than the code being canceled.
DD: You have one cancel token with long lifetime and components with shorter lifetime
YK: In Ember's cases, you rapidly get into situations where the cancelation is complicated to thread, e.g., async methods.
DT: You end up creating links at different points in lifecycles
DD: So there are good use cases, for CancelToken.some.
Strike: "Still unsure what the exact use cases are, but it seems plausible."
DD: So does anyone need CancelToken.every? .NET doesn't have it.
DT: Never needed it [in Midori]
YK: We should think about it because it's symmetric
DT: It's asymmetric; cancelation is monotonoic. We just don't get this pattern in Midori.
SP: Doesn't sound useful
DT: You might end up with some nice usages of 'some', so it is a good thing to have.
RW: Why not call it CancelToken.all?
DD: I should think about that harder; there was some argument about all rather than every. Anyway, this is more about 'some' given that 'every' is not useful.
RW: In favor of 'all': For explanation purposes, it would be nice to have this analogy. Apply what you already know.
YK: I have become comfortable with a cancel token as a parameter.
DD: The concern Yehuda has raised is, the semantic burden on developers of threading the cancel tokens through all the APIs, and changing all the signatures, is an issue. Should we mostly do options objects or bare parameters?
YK: Seems difficult to have a universal convention
DD: In .NET you have static types and overloads so it's easier.
DD: YK's idea was to introduce syntax for allowing cancelTokens and awaits to work better together:
```js
async function cancelMe(cancelToken) {
doSyncThing();
await doAsyncUncancelableThing(cancelToken);
await anotherOne(cancelToken);
}
```
To...
```js
async function cancelMe() {
doSyncThing();
await doAsyncUncancelableThing(await.cancelToken);
await anotherOne(await.cancelToken);
}
```
YK: This would continue with our tradition of implicit parameters, e.g. implicitly passing 'this'. You don't want to have to add it explicitly
YK:
```js
async function cancelMe() {
doSyncThing();
await doAsyncUncancelableThing(await.cancelToken);
await anotherOne(await.cancelToken);
}
let [cancelToken, promise] = [some ambiguous token] fetch(...);
```
MM: What would this correspond to with explicit characterization?
```js
function fetch() {
return await.cancelToken;
}
```
YK: There is a pervasive threading problem. This is analogous to new.target.
YK: `[some ambiguous token]` is the machinery that represents the longhand that Domenic showed
```js
let token = new CancelToken(function(c) {
});
function fetch(
@Yehuda, can you fill in this example with some code that illustrates whatever you were going to write,
```
DD: What I'm hearing is that people are not heavily concerned. Sounds like this might be worth pursuing. Cancelation already has a lot of stuff in it, and it's hard to get a read on how many people are going to have objections. Dean already raised several objections and we didn't have time in the timebox to raise all of them.
DT: good effort and really want something along the lines
YK: If the implicit argument fails, I'm not sure whether I'll be OK with this whole proposal.
DD: There is some enthusiasm for this proposal, it seems, including some of the additions. More is available in the repo. I'll add more spec'd things, including await.cancelToken, Promise.cancelable, and CancelToken.any
BT: What do cancelable promises change about async functions? Seems purely additive.
DD: Yes, seems purely additive. We don't have third state.
YK: It'd be possible for await to send cancelation tokens, but only if you do extra things to thread things through.
BT: Another question about Domenic's proposal: Is the rationale for why third state is bad documented?