Skip to content

Commit

Permalink
More detail on why events should fire before promises (#460)
Browse files Browse the repository at this point in the history
* More detail on why events should fire before promises

* Update index.bs

* Update index.bs

Co-authored-by: Martin Thomson <[email protected]>

* Update index.bs

Co-authored-by: Martin Thomson <[email protected]>

* Update index.bs

Co-authored-by: Martin Thomson <[email protected]>

* Update index.bs

Co-authored-by: Martin Thomson <[email protected]>

---------

Co-authored-by: Lea Verou <[email protected]>
Co-authored-by: Martin Thomson <[email protected]>
  • Loading branch information
3 people authored Apr 1, 2024
1 parent 222226d commit 12d02ab
Showing 1 changed file with 11 additions and 6 deletions.
17 changes: 11 additions & 6 deletions index.bs
Original file line number Diff line number Diff line change
Expand Up @@ -1864,17 +1864,22 @@ Follow the <a href="https://www.w3.org/2001/tag/doc/promises-guide#one-time-even
in the <strong><a href="https://www.w3.org/2001/tag/doc/promises-guide">Writing
Promise-Using Specifications</a></strong> guideline.

<h3 id="promises-and-events">Events should fire before Promises resolve</h3>
<h3 id="promises-and-events">Events should fire before related Promises resolve</h3>

If a Promise-based asynchronous algorithm dispatches events,
it should dispatch them before the Promise resolves,
rather than after.

This guarantees that once the Promise resolves,
all effects of the algorithm have been applied.
For example, if an author changes some state
in reaction to an event which the Promise dispatches,
they can be sure that all of the state is consistent if the Promise is resolved.
When a promise is resolved, a <a href=https://html.spec.whatwg.org/multipage/webappapis.html#microtask>microtask</a> is queued to run its reaction callbacks.
Microtasks are processed when the JavaScript stack empties.
<a href=https://dom.spec.whatwg.org/#dispatching-events>Dispatching an event</a> is synchronous,
which involves the JavaScript stack emptying between each listener.
As a result, if a promise is resolved before dispatching a related event,
any microtasks that are scheduled in reaction to a promise
will be invoked between the first and second listeners of the event.

Dispatching the event first prevents this interleaving.
All event listeners are then invoked before any promise reaction callbacks.

<h3 id="dont-invent-event-like">Don’t invent your own event listener-like infrastructure</h3>

Expand Down

0 comments on commit 12d02ab

Please sign in to comment.