Skip to content

Commit 5fdfcfb

Browse files
committed
Don't require action within a Promise reaction microtask.
1 parent 7861814 commit 5fdfcfb

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

index.bs

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1965,6 +1965,38 @@ See also:
19651965

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

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

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

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

21362172
If a Promise-based asynchronous algorithm dispatches events,

0 commit comments

Comments
 (0)