await Promise.delay(2000)
// resolves after _at least_ 2000 ms, same as setTimeout
await Promise.timeout(fetchTaskPromise, 2000)
// rejects after 2000ms if fetchTaskPromise not resolved
I previously posted this in tc39 discussion. https://es.discourse.group/t/promise-delay-sleep-and-promise-timeout/349
But it’s hard to specify it in the ES spec so I post this in WICG hope we can use it in the Web.
Like the idea, but I have a couple suggestions:
- This should be attached to the window, not
Promise
, to align with other DOM APIs.
- I’m not convinced we should have a separate
.delay
and .timeout
- that’s just Promise.race([fetchTaskPromise, delay(2000)])
. Instead, this should really integrate with AbortSignal
somehow.
2 Likes
See https://github.com/whatwg/html/issues/617 for the Promise.delay
equivalent.
I am happy to specify this if we have any implementation interest. (And I agree it would be on Window
, or more likely WindowOrWorkerGlobalScope
, not on Promise
. Another reason is that certain host environments, like worklets, want to prevent clock-dependent behavior, so having this in the language would be bad.) It would also be abortable using AbortSignal
, per the above-linked thread.
For your Promise.timeout
, I suggest AbortSignal.timeout(2000)
, used like so:
fetch(url, { signal: AbortSignal.timeout(2000) })
(maybe AbortSignal.after
would be a reasonable name too.) For that, the next step would be filing an issue on https://github.com/whatwg/dom/issues and working toward implementer interest. This was previously discussed a bit in https://github.com/whatwg/fetch/issues/951#issuecomment-541369940. Again, I am happy to specify this if we have any implementation interest.
1 Like
Hi! @domenic My spec writes:
The interpretation of afterTime is depending on the host. Host can return AbortCompletion if the environment does not allow clock-dependent behaviors or afterTime is invalid value.
With this spec text, it is possible to “certain host environments, like worklets, want to prevent clock-dependent behavior
”
1 Like