Skip to content

Commit

Permalink
feat: defered promise util
Browse files Browse the repository at this point in the history
Changelog: feature
  • Loading branch information
mrspartak committed Jun 22, 2024
1 parent 6869655 commit 28273ca
Show file tree
Hide file tree
Showing 3 changed files with 51 additions and 1 deletion.
19 changes: 19 additions & 0 deletions examples/deferred.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { deferred } from "@mrspartak/promises"
import { readStream } from "./stream"

// Create a deferred promise
const { promise, resolve, reject } = deferred<void>()

// Read the stream in chunks and then resolve the promise
const stream = await readStream()
let data = ''
stream.on('data', (chunk) => {
data += chunk
})
stream.on('end', () => {
resolve()
})

// Resolve the promise with the data
await promise
console.log(data) // Data is ready
30 changes: 30 additions & 0 deletions src/deferred.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
/**
* Represents a deferred promise, which exposes the resolve and reject functions.
*
* @template T The type of the value that the promise resolves to.
*/
export type DeferredOut<T> = {
promise: Promise<T>;
resolve: (value: T | PromiseLike<T>) => void;
reject: (reason?: any) => void;
};

/**
* Creates a deferred promise, allowing manual resolution or rejection.
*
* @template T The type of the value that the promise resolves to.
* @returns {DeferredOut<T>} An object containing the promise, resolve, and reject functions.
*
* @includeExample examples/deferred.ts
*/
export function deferred<T>(): DeferredOut<T> {
let resolve!: (value: T | PromiseLike<T>) => void;
let reject!: (reason?: any) => void;

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

return { promise, resolve, reject };
}
3 changes: 2 additions & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { to } from "./to";
import { delay, sleep } from "./delay";
import { timeout } from "./timeout";
import { deferred } from "./deferred";

export { to, delay, sleep, timeout };
export { to, delay, sleep, timeout, deferred };

0 comments on commit 28273ca

Please sign in to comment.