Skip to content

Commit

Permalink
Add withResolvers
Browse files Browse the repository at this point in the history
  • Loading branch information
Minhir authored and aleclarson committed Aug 13, 2024
1 parent 249ea56 commit 3dc862c
Show file tree
Hide file tree
Showing 4 changed files with 66 additions and 0 deletions.
16 changes: 16 additions & 0 deletions docs/async/withResolvers.mdx
Original file line number Diff line number Diff line change
@@ -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)
```
30 changes: 30 additions & 0 deletions src/async/withResolvers.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
interface PromiseWithResolvers<T> {
promise: Promise<T>
resolve: (value: T | PromiseLike<T>) => 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<T>(): PromiseWithResolvers<T> {
let resolve: any
let reject: any

const promise = new Promise<T>((res, rej) => {
resolve = res
reject = rej
})

return { resolve, reject, promise }
}
1 change: 1 addition & 0 deletions src/mod.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand Down
19 changes: 19 additions & 0 deletions tests/async/withResolvers.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import * as _ from 'radashi'

describe('withResolvers', () => {
test('resolves promise', async () => {
const { resolve, promise } = _.withResolvers<number>()

resolve(42)

expect(await promise).toBe(42)
})

test('rejects promise', async () => {
const { reject, promise } = _.withResolvers<number>()

reject('Weird error')

await expect(promise).rejects.toThrowError('Weird error')
})
})

0 comments on commit 3dc862c

Please sign in to comment.