universalify
Make a callback- or promise-based function support both promises and callbacks.
Last updated a year ago by ryanzim .
MIT · Repository · Bugs · Original npm · Tarball · package.json
$ gnpm install universalify 
SYNC missed versions from official npm registry.

universalify

GitHub Workflow Status (branch) Coveralls github branch npm npm

Make a callback- or promise-based function support both promises and callbacks.

Uses the native promise implementation.

Installation

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.

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.

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

Current Tags

  • 2.0.1                                ...           latest (a year ago)

8 Versions

  • 2.0.1                                ...           a year ago
  • 2.0.0                                ...           4 years ago
  • 1.0.0                                ...           5 years ago
  • 0.2.0                                ...           5 years ago
  • 0.1.2                                ...           6 years ago
  • 0.1.1                                ...           7 years ago
  • 0.1.0                                ...           8 years ago
  • 0.0.1                                ...           8 years ago
Maintainers (1)
Downloads
Today 0
This Week 0
This Month 0
Last Day 0
Last Week 0
Last Month 0
Dependencies (0)
None
Dev Dependencies (5)
Dependents (3)

Copyright 2013 - present © cnpmjs.org | Home |