Re: [whatwg/dom] Expose an `aborted` promise on AbortSignal? (#946)

Here's my understanding of the problem: An async task uses a signal to know when/if the task should be aborted. The listener the async task adds to the signal is no longer needed once the task is over, or once the listener is called (which should also end the task). However, the listener added by the async task ends up in reference as long as the signal is still in reference, which in some cases is much longer than necessary, since the signal's lifetime extends beyond the single async task.

So, a solution needs to have some knowledge of the async task.

Here's the solution from @benjamingr:

> ```js
> // after
> async function setTimeout(ms, { signal } = {}) {
>   return await new Promise((resolve) => {
>     const timer = setTimeout(() => {
>       resolve();
>     }, ms);
>     // works in Node.js since timers are objects
>     aborted(signal, timer).then(() => clearTimeout(timer) || resolve(Promise.reject(new AbortError()))); 
>   });
> }
> ```

(I removed a `|| ||` from the code above, sorry if that's part of an upcoming proposal I'm not aware of)

I'm really struggling to understand how the above works. I'm never the smartest developer in the room, but I think others would struggle with it too.

In the above, assuming the reference that the body of `aborted` has to `timer` is weak, `timer` is out of reference once the promise returned by `aborted(signal, timer)` rejects, fulfills and its reaction callback is called, or the promise loses the ability to fulfill or reject due to other things going out of reference. It fulfills if the signal is aborted, but I don't understand when the other things can happen. From other comments in the thread, it seems like finalization of the `timer` object is used in some way, but it seems circular. What am I missing?

-- 
You are receiving this because you are subscribed to this thread.
Reply to this email directly or view it on GitHub:
https://github.com/whatwg/dom/issues/946#issuecomment-773935100

Received on Friday, 5 February 2021 10:11:35 UTC