WICG / cookie-store

Asynchronous access to cookies from JavaScript
https://wicg.github.io/cookie-store/
Apache License 2.0
144 stars 35 forks source link

CookieChangeEvent vs. promise resolve - what's the correct order? #240

Open bakulf opened 1 month ago

bakulf commented 1 month ago
cookieStore.onchange = () => console.log("CHANGE");
await cookieStore.set('cookie-name', 'cookie-value');
console.log("RESOLVED");

What's the correct sequence of console log messages? The spec needs to be clarified. On Chrome, sometimes you see CHANGE+RESOLVED, and sometimes RESOLVED+CHANGE, which is confusing for developers.

In Firefox, the promise is always resolved before dispatching the CookieChangeEvent.

annevk commented 1 month ago

What if you end up calling set() multiple times? I wonder if this relates to #230 somehow.

Naively:

  1. You call set()
  2. It goes in parallel.
  3. It stores something and knows that succeeded.
  4. It now queues a task to a) resolve the promise and b) fire a change event.
  5. As there is no JS on the stack, the event callbacks run before the promise callbacks?

Not sure if that's ideal though. I feel like the order between events and promises is still something we haven't really settled in general. cc @jakearchibald @domenic

jakearchibald commented 1 month ago

https://w3ctag.github.io/design-principles/#promises-and-events

  1. It now queues a task to a) resolve the promise and b) fire a change event.
  2. As there is no JS on the stack, the event callbacks run before the promise callbacks?

That's true for the first event callback, since events are dispatched synchronously. But since there's a microtask checkpoint after invoking a callback, the promise reaction callbacks are called after the first listener, but before the second (and third etc etc).

If you fire the event before resolving the promise, all event callbacks are called consistently before any of the promise reaction callbacks. That's why it's important to do events first.