Skip to content

Commit

Permalink
feat(promise-utils): add makeDeferred function
Browse files Browse the repository at this point in the history
  • Loading branch information
simonmumenthaler committed Dec 8, 2023
1 parent ed2673f commit a91f11a
Show file tree
Hide file tree
Showing 3 changed files with 54 additions and 0 deletions.
1 change: 1 addition & 0 deletions packages/utilities/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ export * from './lib/json-stringify-replacer/json-stringify-replacer.function.js
export * from './lib/map-values-deep/map-values-deep.js'
export * from './lib/object/omit-props.function.js'
export * from './lib/object/pick-props.function.js'
export * from './lib/promise/make-deferred.function.js'
export * from './lib/random-int/random-int.js'
export * from './lib/tag/get-tag.function.js'
export * from './lib/tag/tag.enum.js'
Expand Down
23 changes: 23 additions & 0 deletions packages/utilities/src/lib/promise/make-deferred.function.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { describe, expect, test } from '@jest/globals'
import { makeDeferred } from './make-deferred.function.js'

describe('makeDeferred', () => {

test('returns an object containing a promise', () => {
const { promise } = makeDeferred()
expect(promise).toBeInstanceOf(Promise)
})

test('resolves the returned promise with the returned resolveFn', async () => {
const { promise, resolve } = makeDeferred()
resolve('foo')
await expect(promise).resolves.toBe('foo')
})

test('rejects the returned promise with the returned rejectFn', async () => {
const { promise, reject } = makeDeferred()
reject(new Error('Foo Bar'))
await expect(promise).rejects.toThrow('Foo Bar')
})

})
30 changes: 30 additions & 0 deletions packages/utilities/src/lib/promise/make-deferred.function.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
export interface Deferred<T> {
resolve: (value: T | PromiseLike<T>) => void
reject: (reason: unknown) => void
promise: Promise<T>
}

/**
* returns a `deferred` object which contains a promise and its resolve/reject functions
* @example ```ts
* const deferred = new makeDeferred<string>()
*
* // use promise
* deferred.promise.then(console.log, console.error)
*
* // resolve
* deferred.resolve('a value')
*
* // reject
* deferred.reject(new Error('oh no!'))
* ```
*/
export function makeDeferred<T>(): Deferred<T> {
const deferred: Deferred<T> = <any>{}

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

0 comments on commit a91f11a

Please sign in to comment.