Skip to content

Commit b756257

Browse files
jan-ivarjyasskin
authored andcommitted
Don't require action within a Promise reaction microtask.
1 parent 2dacfea commit b756257

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

index.bs

+36
Original file line numberDiff line numberDiff line change
@@ -1966,6 +1966,38 @@ See also:
19661966

19671967
* <a href="https://www.w3.org/2001/tag/doc/promises-guide">Writing Promise-Using Specifications</a>
19681968

1969+
<h4 id="sync-callbacks">When to use callback functions instead</h4>
1970+
1971+
<p>If an algorithm requires that callback functions respond
1972+
synchronously (e.g. to take or veto some action), then that is a
1973+
synchronous API, and should not be modelled with a promise. Instead,
1974+
use an explicit callback or event.</p>
1975+
1976+
<p>In Promise reaction callbacks, you may not require action within
1977+
the same microtask.</p>
1978+
1979+
<p>This protects promise composition: patterns like <code>await</code>,
1980+
wrapper helpers, logging, <code>Promise.race()</code>, or multiple
1981+
<code>.then()</code> branches all queue an extra microtask and must
1982+
not cause action at a distance.</p>
1983+
1984+
<div class=example>
1985+
Calling <code>event.preventDefault()</code> in an event handler,
1986+
or choosing a response object inside a
1987+
<code>fetchEvent.respondWith()</code> callback.
1988+
</div>
1989+
<div class="example">
1990+
A non-event example is the [captureController.setFocusBehavior()](https://w3c.github.io/mediacapture-screen-share/#dom-capturecontroller-setfocusbehavior)
1991+
method to push a window the user has chosen to screen-capture, to
1992+
the front. Applications can decide this based on the window chosen.
1993+
But any delay risks click-jacking.
1994+
1995+
Instead of requiring the method be called synchronously on the
1996+
reaction microtask of the promise from `getDisplayMedia()`, the
1997+
solution was to instead require the method be called on the
1998+
same promise reaction task, with a one second timeout.
1999+
</div>
2000+
19692001
<h3 id="aborting">Cancel asynchronous APIs/operations using AbortSignal</h3>
19702002

19712003
If an asynchronous method can be cancelled,
@@ -2132,6 +2164,10 @@ Follow the <a href="https://www.w3.org/2001/tag/doc/promises-guide#one-time-even
21322164
in the <strong><a href="https://www.w3.org/2001/tag/doc/promises-guide">Writing
21332165
Promise-Using Specifications</a></strong> guideline.
21342166

2167+
<h3 id="promises-and-reaction">Don't use promises for cancelable events</h3>
2168+
2169+
See <a href="#sync-callbacks">when to use callback functions instead</a>.
2170+
21352171
<h3 id="promises-and-events">Events should fire before related Promises resolve</h3>
21362172

21372173
If a Promise-based asynchronous algorithm dispatches events,

0 commit comments

Comments
 (0)