finki-main
main
|
Last change
on this file since 81bc7da was 81bc7da, checked in by Klimentina Efremova <klimentina08642@…>, 3 months ago |
|
Initial commit
|
-
Property mode
set to
100644
|
|
File size:
1.4 KB
|
| Line | |
|---|
| 1 | # @gar/promisify
|
|---|
| 2 |
|
|---|
| 3 | ### Promisify an entire object or class instance
|
|---|
| 4 |
|
|---|
| 5 | This module leverages es6 Proxy and Reflect to promisify every function in an
|
|---|
| 6 | object or class instance.
|
|---|
| 7 |
|
|---|
| 8 | It assumes the callback that the function is expecting is the last
|
|---|
| 9 | parameter, and that it is an error-first callback with only one value,
|
|---|
| 10 | i.e. `(err, value) => ...`. This mirrors node's `util.promisify` method.
|
|---|
| 11 |
|
|---|
| 12 | In order that you can use it as a one-stop-shop for all your promisify
|
|---|
| 13 | needs, you can also pass it a function. That function will be
|
|---|
| 14 | promisified as normal using node's built-in `util.promisify` method.
|
|---|
| 15 |
|
|---|
| 16 | [node's custom promisified
|
|---|
| 17 | functions](https://nodejs.org/api/util.html#util_custom_promisified_functions)
|
|---|
| 18 | will also be mirrored, further allowing this to be a drop-in replacement
|
|---|
| 19 | for the built-in `util.promisify`.
|
|---|
| 20 |
|
|---|
| 21 | ### Examples
|
|---|
| 22 |
|
|---|
| 23 | Promisify an entire object
|
|---|
| 24 |
|
|---|
| 25 | ```javascript
|
|---|
| 26 |
|
|---|
| 27 | const promisify = require('@gar/promisify')
|
|---|
| 28 |
|
|---|
| 29 | class Foo {
|
|---|
| 30 | constructor (attr) {
|
|---|
| 31 | this.attr = attr
|
|---|
| 32 | }
|
|---|
| 33 |
|
|---|
| 34 | double (input, cb) {
|
|---|
| 35 | cb(null, input * 2)
|
|---|
| 36 | }
|
|---|
| 37 |
|
|---|
| 38 | const foo = new Foo('baz')
|
|---|
| 39 | const promisified = promisify(foo)
|
|---|
| 40 |
|
|---|
| 41 | console.log(promisified.attr)
|
|---|
| 42 | console.log(await promisified.double(1024))
|
|---|
| 43 | ```
|
|---|
| 44 |
|
|---|
| 45 | Promisify a function
|
|---|
| 46 |
|
|---|
| 47 | ```javascript
|
|---|
| 48 |
|
|---|
| 49 | const promisify = require('@gar/promisify')
|
|---|
| 50 |
|
|---|
| 51 | function foo (a, cb) {
|
|---|
| 52 | if (a !== 'bad') {
|
|---|
| 53 | return cb(null, 'ok')
|
|---|
| 54 | }
|
|---|
| 55 | return cb('not ok')
|
|---|
| 56 | }
|
|---|
| 57 |
|
|---|
| 58 | const promisified = promisify(foo)
|
|---|
| 59 |
|
|---|
| 60 | // This will resolve to 'ok'
|
|---|
| 61 | promisified('good')
|
|---|
| 62 |
|
|---|
| 63 | // this will reject
|
|---|
| 64 | promisified('bad')
|
|---|
| 65 | ```
|
|---|
Note:
See
TracBrowser
for help on using the repository browser.