Created
July 18, 2023 17:57
-
-
Save lmammino/ef121da874a80d657379a1cd64bf8166 to your computer and use it in GitHub Desktop.
Promise.withResolvers() polyfill
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
if (typeof Promise.withResolvers === 'undefined') { | |
Promise.withResolvers = function () { | |
let resolve, reject | |
const promise = new Promise((res, rej) => { | |
resolve = res | |
reject = rej | |
}) | |
return { promise, resolve, reject } | |
} | |
} | |
// Usage: | |
// const { promise, resolve, reject } = Promise.withResolvers() | |
// console.log(promise, resolve, reject) // Promise { <pending> } [Function (anonymous)] [Function (anonymous)] | |
// ... Do something async and then call resolve or reject! |
A TypeScript version:
if (typeof Promise.withResolvers === "undefined") {
Promise.withResolvers = <T>() => {
let resolve: (value: T | PromiseLike<T>) => void;
let reject: (reason?: unknown) => void;
const promise = new Promise<T>((res, rej) => {
resolve = res;
reject = rej;
});
return { promise, resolve: resolve!, reject: reject! };
};
}
@Stadly you can put the !
on the declaration, rather than on the return object.
if (typeof Promise.withResolvers === "undefined") {
Promise.withResolvers = <T>() => {
let resolve!: (value: T | PromiseLike<T>) => void;
let reject!: (reason?: unknown) => void;
const promise = new Promise<T>((res, rej) => {
resolve = res;
reject = rej;
});
return { promise, resolve, reject };
};
}
Thanks, @WORMSS! I was not aware :)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@lmammino this is not working:
With this error:
But I see that it is because of the name that I am reassigning the variable inside the function, not the one outside. It's totally my fault. Sorry about that.