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