feat(core): Add fromCallback utility function for promisifying Node.js-style callback functions
This commit is contained in:
@ -3,6 +3,6 @@
|
||||
*/
|
||||
export const commitinfo = {
|
||||
name: '@push.rocks/smartpromise',
|
||||
version: '4.0.4',
|
||||
version: '4.1.0',
|
||||
description: 'A TypeScript library for managing promises and Deferred constructs, simplifying asynchronous programming.'
|
||||
}
|
||||
|
19
ts/index.ts
19
ts/index.ts
@ -80,3 +80,22 @@ export const getFirstTrueOrFalse = async (promisesArg: Promise<boolean>[]) => {
|
||||
});
|
||||
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
|
||||
}
|
||||
});
|
||||
});
|
||||
};
|
||||
|
Reference in New Issue
Block a user