Skip to content
Source
Sign inSign up
TanStack/db
Open History to see the last commit

deferred.ts

47 lines1.1 KB

1/**
2 * A Deferred object represents a Promise that can be resolved or rejected
3 * from outside the Promise constructor.
4 */
5export interface Deferred<T> {
6 /** The Promise object being controlled */
7 promise: Promise<T>
8​
9 /** Function to resolve the Promise with a value or another Promise */
10 resolve: (value: T | PromiseLike<T>) => void
11​
12 /** Function to reject the Promise with an error */
13 reject: (reason?: Error | unknown) => void
14​
15 /** Check if the Promise has been resolved or rejected */
16 isPending: () => boolean
18​
19/**
20 * Creates a Deferred object containing a Promise and methods to control it.
21 *
22 * @returns A Deferred object with promise, resolve, reject, and isPending methods
23 */
24export function createDeferred<T>(): Deferred<T> {
25 let resolve!: (value: T | PromiseLike<T>) => void
26 let reject!: (reason?: Error | unknown) => void
27 let isPending = true
28​
29 const promise = new Promise<T>((res, rej) => {
30 resolve = (value) => {
31 isPending = false
32 res(value)
33 }
34​
35 reject = (reason) => {
36 isPending = false
37 rej(reason)
38 }
39 })
40​
41 return {
42 promise,
43 resolve,
44 reject,
45 isPending: () => isPending,
46 }