Files
smartpromise/ts/index.ts
T

96 lines
2.6 KiB
TypeScript

import { defer } from './smartpromise.classes.deferred.js';
export * from './smartpromise.classes.cumulativedeferred.js';
export * from './smartpromise.classes.deferred.js';
export function resolvedPromise(): Promise<void>;
export function resolvedPromise<T>(value: T): Promise<T>;
/**
* Creates a new resolved promise for the provided value.
*/
export function resolvedPromise<T>(value?: T): Promise<T | void> {
return Promise.resolve(value);
}
/**
* Creates a new rejected promise for the provided reason.
*/
export const rejectedPromise = (err: unknown): Promise<never> => {
return Promise.reject(err);
};
interface IAsyncFunction<TInput, TOutput> {
(someArg: TInput): Promise<TOutput>;
}
/**
* accepts an array of inputs and a function that accepts the input.
* runs all items with the function and returns the result array when all items have run
* @param inputArg
* @param functionArg
*/
export const map = async <TInput, TOutput = TInput>(
inputArg: TInput[],
functionArg: IAsyncFunction<TInput, TOutput>
): Promise<TOutput[]> => {
return Promise.all(inputArg.map(functionArg));
};
export const timeoutWrap = async <T = unknown>(
promiseArg: Promise<T>,
timeoutInMsArg: number,
rejectArg = true
): Promise<T | null> => {
return new Promise<T | null>((resolve, reject) => {
setTimeout(() => {
if (rejectArg) {
reject(new Error('timeout'));
} else {
resolve(null);
}
}, timeoutInMsArg);
promiseArg.then(resolve, reject);
});
};
export const timeoutAndContinue = async <T = unknown>(
promiseArg: Promise<T>,
timeoutInMsArg = 60000
): Promise<T | null> => {
return timeoutWrap(promiseArg, timeoutInMsArg, false);
};
export const getFirstTrueOrFalse = async (promisesArg: Promise<boolean>[]): Promise<boolean> => {
const done = defer<boolean>();
for (const promiseArg of promisesArg) {
promiseArg.then((resultArg) => {
if (resultArg === true) {
done.resolve(true);
}
});
}
Promise.all(promisesArg).then(() => {
done.resolve(false);
});
return done.promise;
};
/**
* Converts a Node.js-style callback-based function into a Promise.
* @param fn The function that expects a callback.
* @returns A Promise that resolves with the result of the function or rejects with an error.
*/
export const fromCallback = <T>(
fn: (callback: (err: NodeJS.ErrnoException | null, result?: T) => void) => void
): Promise<T> => {
return new Promise((resolve, reject) => {
fn((err, result) => {
if (err) {
reject(err); // Reject the promise with the error
} else {
resolve(result as T); // Resolve the promise with the result
}
});
});
};