diff --git a/docs/async/withResolvers.mdx b/docs/async/withResolvers.mdx new file mode 100644 index 00000000..e5dcd099 --- /dev/null +++ b/docs/async/withResolvers.mdx @@ -0,0 +1,16 @@ +--- +title: withResolvers +description: Ponyfill for Promise.withResolvers() +--- + +### Usage + +Creates a new promise and returns the resolve and reject functions along with the promise itself. + +The ponyfill for https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/withResolvers + +```ts +const { resolve, reject, promise } = withResolvers() + +resolve(42) +``` diff --git a/src/async/withResolvers.ts b/src/async/withResolvers.ts new file mode 100644 index 00000000..a5a24f33 --- /dev/null +++ b/src/async/withResolvers.ts @@ -0,0 +1,30 @@ +interface PromiseWithResolvers { + promise: Promise + resolve: (value: T | PromiseLike) => void + reject: (reason?: any) => void +} + +/** + * Creates a new promise and returns the resolve and reject functions along with the promise itself. + * + * The ponyfill for https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/withResolvers + * + * @see https://radashi-org.github.io/reference/async/withResolvers + * @example + * ```ts + * const {resolve, reject, promise} = withResolvers() + * + * resolve(42) + * ``` + */ +export function withResolvers(): PromiseWithResolvers { + let resolve: any + let reject: any + + const promise = new Promise((res, rej) => { + resolve = res + reject = rej + }) + + return { resolve, reject, promise } +} diff --git a/src/mod.ts b/src/mod.ts index ae47f9bf..0720a12c 100644 --- a/src/mod.ts +++ b/src/mod.ts @@ -39,6 +39,7 @@ export * from './async/reduce.ts' export * from './async/retry.ts' export * from './async/sleep.ts' export * from './async/tryit.ts' +export * from './async/withResolvers.ts' export * from './curry/callable.ts' export * from './curry/chain.ts' diff --git a/tests/async/withResolvers.test.ts b/tests/async/withResolvers.test.ts new file mode 100644 index 00000000..c5adbaed --- /dev/null +++ b/tests/async/withResolvers.test.ts @@ -0,0 +1,19 @@ +import * as _ from 'radashi' + +describe('withResolvers', () => { + test('resolves promise', async () => { + const { resolve, promise } = _.withResolvers() + + resolve(42) + + expect(await promise).toBe(42) + }) + + test('rejects promise', async () => { + const { reject, promise } = _.withResolvers() + + reject('Weird error') + + await expect(promise).rejects.toThrowError('Weird error') + }) +})