polyfills: add Promise.withResolver

This commit is contained in:
thislight 2024-12-04 22:57:41 +08:00
parent bffa896184
commit 0fca81dc93
No known key found for this signature in database
GPG key ID: FCFE5192241CCD4E
2 changed files with 47 additions and 0 deletions

View file

@ -15,3 +15,24 @@ if (typeof window.crypto.randomUUID === "undefined") {
) as `${string}-${string}-${string}-${string}-${string}`;
};
}
if (typeof Promise.withResolvers === "undefined") {
// Chrome/Edge 119, Firefox 121, Safari/iOS 17.4
// Promise.withResolvers is generic and works with subclasses - the typescript built-in decl
// could not handle the subclassing case.
Promise.withResolvers = function <T>(this: AnyPromiseConstructor<T>) {
let resolve!: PromiseWithResolvers<T>["resolve"], reject!: PromiseWithResolvers<T>["reject"];
// These variables are expected to be set after `new this()`
const promise = new this((resolve0, reject0) => {
resolve = resolve0;
reject = reject0;
})
return {
promise, resolve, reject
}
}
}