From 1afbfd8895a661d9ec9e86bf306cfbf350fe04bc Mon Sep 17 00:00:00 2001 From: Philipp Kunz Date: Tue, 7 Jan 2025 04:27:24 +0100 Subject: [PATCH] feat(core): Add fromCallback utility function for promisifying Node.js-style callback functions --- changelog.md | 8 +++++--- ts/00_commitinfo_data.ts | 2 +- ts/index.ts | 19 +++++++++++++++++++ 3 files changed, 25 insertions(+), 4 deletions(-) diff --git a/changelog.md b/changelog.md index e3a9776..89a77b4 100644 --- a/changelog.md +++ b/changelog.md @@ -1,5 +1,10 @@ # Changelog +## 2025-01-07 - 4.1.0 - feat(core) +Add fromCallback utility function for promisifying Node.js-style callback functions + +- Added fromCallback function to convert Node.js-style callbacks into Promises. + ## 2024-06-23 - 4.0.4 - fix(ci) Remove .gitlab-ci.yml and update dependencies and metadata @@ -7,8 +12,6 @@ Remove .gitlab-ci.yml and update dependencies and metadata - Updated dependencies in package.json and npmextra.json - Improved description and keywords for better package definition - - ## 2024-05-29 - 4.0.3 - Maintenance Update project configuration and descriptions. @@ -85,4 +88,3 @@ Added polyfill and npmextra.json. Updated continuous integration configuration. - Update ci -``` diff --git a/ts/00_commitinfo_data.ts b/ts/00_commitinfo_data.ts index dc258c9..69ff375 100644 --- a/ts/00_commitinfo_data.ts +++ b/ts/00_commitinfo_data.ts @@ -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.' } diff --git a/ts/index.ts b/ts/index.ts index e193b45..08eeece 100644 --- a/ts/index.ts +++ b/ts/index.ts @@ -80,3 +80,22 @@ export const getFirstTrueOrFalse = async (promisesArg: Promise[]) => { }); 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 = ( + fn: (callback: (err: NodeJS.ErrnoException | null, result?: T) => void) => void +): Promise => { + 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 + } + }); + }); +};