https://github.com/RyanZim/universalify
Make a callback- or promise-based function support both promises and callbacks.
https://github.com/RyanZim/universalify
callbacks js nodejs promises
Last synced: 8 days ago
JSON representation
Make a callback- or promise-based function support both promises and callbacks.
- Host: GitHub
- URL: https://github.com/RyanZim/universalify
- Owner: RyanZim
- License: mit
- Created: 2017-04-08T17:22:57.000Z (about 8 years ago)
- Default Branch: master
- Last Pushed: 2023-11-01T17:12:25.000Z (over 1 year ago)
- Last Synced: 2025-04-02T03:02:07.962Z (17 days ago)
- Topics: callbacks, js, nodejs, promises
- Language: JavaScript
- Size: 18.6 KB
- Stars: 111
- Watchers: 2
- Forks: 14
- Open Issues: 1
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
- awesome-github-star - universalify - or promise-based function support both promises and callbacks. | RyanZim | 106 | (JavaScript)
README
# universalify



Make a callback- or promise-based function support both promises and callbacks.
Uses the native promise implementation.
## Installation
```bash
npm install universalify
```## API
### `universalify.fromCallback(fn)`
Takes a callback-based function to universalify, and returns the universalified function.
Function must take a callback as the last parameter that will be called with the signature `(error, result)`. `universalify` does not support calling the callback with three or more arguments, and does not ensure that the callback is only called once.
```js
function callbackFn (n, cb) {
setTimeout(() => cb(null, n), 15)
}const fn = universalify.fromCallback(callbackFn)
// Works with Promises:
fn('Hello World!')
.then(result => console.log(result)) // -> Hello World!
.catch(error => console.error(error))// Works with Callbacks:
fn('Hi!', (error, result) => {
if (error) return console.error(error)
console.log(result)
// -> Hi!
})
```### `universalify.fromPromise(fn)`
Takes a promise-based function to universalify, and returns the universalified function.
Function must return a valid JS promise. `universalify` does not ensure that a valid promise is returned.
```js
function promiseFn (n) {
return new Promise(resolve => {
setTimeout(() => resolve(n), 15)
})
}const fn = universalify.fromPromise(promiseFn)
// Works with Promises:
fn('Hello World!')
.then(result => console.log(result)) // -> Hello World!
.catch(error => console.error(error))// Works with Callbacks:
fn('Hi!', (error, result) => {
if (error) return console.error(error)
console.log(result)
// -> Hi!
})
```## License
MIT