UNPKG

2.01 kBMarkdownView Raw
1# universalify
2
3![GitHub Workflow Status (branch)](https://img.shields.io/github/actions/workflow/status/RyanZim/universalify/ci.yml?branch=master)
4![Coveralls github branch](https://img.shields.io/coveralls/github/RyanZim/universalify/master.svg)
5![npm](https://img.shields.io/npm/dm/universalify.svg)
6![npm](https://img.shields.io/npm/l/universalify.svg)
7
8Make a callback- or promise-based function support both promises and callbacks.
9
10Uses the native promise implementation.
11
12## Installation
13
14```bash
15npm install universalify
16```
17
18## API
19
20### `universalify.fromCallback(fn)`
21
22Takes a callback-based function to universalify, and returns the universalified function.
23
24Function 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.
25
26```js
27function callbackFn (n, cb) {
28 setTimeout(() => cb(null, n), 15)
29}
30
31const fn = universalify.fromCallback(callbackFn)
32
33// Works with Promises:
34fn('Hello World!')
35.then(result => console.log(result)) // -> Hello World!
36.catch(error => console.error(error))
37
38// Works with Callbacks:
39fn('Hi!', (error, result) => {
40 if (error) return console.error(error)
41 console.log(result)
42 // -> Hi!
43})
44```
45
46### `universalify.fromPromise(fn)`
47
48Takes a promise-based function to universalify, and returns the universalified function.
49
50Function must return a valid JS promise. `universalify` does not ensure that a valid promise is returned.
51
52```js
53function promiseFn (n) {
54 return new Promise(resolve => {
55 setTimeout(() => resolve(n), 15)
56 })
57}
58
59const fn = universalify.fromPromise(promiseFn)
60
61// Works with Promises:
62fn('Hello World!')
63.then(result => console.log(result)) // -> Hello World!
64.catch(error => console.error(error))
65
66// Works with Callbacks:
67fn('Hi!', (error, result) => {
68 if (error) return console.error(error)
69 console.log(result)
70 // -> Hi!
71})
72```
73
74## License
75
76MIT