Merge pull request #64 from DanielRamosAcosta/add-promisify-snippet
Add promisify snippet
This commit is contained in:
19
README.md
19
README.md
@ -46,6 +46,7 @@
|
|||||||
* [Percentile](#percentile)
|
* [Percentile](#percentile)
|
||||||
* [Pipe](#pipe)
|
* [Pipe](#pipe)
|
||||||
* [Powerset](#powerset)
|
* [Powerset](#powerset)
|
||||||
|
* [Promisify](#promisify)
|
||||||
* [Random integer in range](#random-integer-in-range)
|
* [Random integer in range](#random-integer-in-range)
|
||||||
* [Random number in range](#random-number-in-range)
|
* [Random number in range](#random-number-in-range)
|
||||||
* [Randomize order of array](#randomize-order-of-array)
|
* [Randomize order of array](#randomize-order-of-array)
|
||||||
@ -461,6 +462,24 @@ const powerset = arr =>
|
|||||||
// powerset([1,2]) -> [[], [1], [2], [2,1]]
|
// powerset([1,2]) -> [[], [1], [2], [2,1]]
|
||||||
```
|
```
|
||||||
|
|
||||||
|
### Promisify
|
||||||
|
|
||||||
|
Creates a promisified version of the given callback-style function. In Node 8+, you
|
||||||
|
can use [`util.promisify`](https://nodejs.org/api/util.html#util_util_promisify_original)
|
||||||
|
|
||||||
|
```js
|
||||||
|
const promisify = func =>
|
||||||
|
(...args) =>
|
||||||
|
new Promise((resolve, reject) =>
|
||||||
|
func(...args, (err, result) =>
|
||||||
|
err
|
||||||
|
? reject(err)
|
||||||
|
: resolve(result))
|
||||||
|
)
|
||||||
|
// const stat = promisify(fs.stat)
|
||||||
|
// stat('foo.txt') -> Promise resolves if `foo.txt` exists, otherwise rejects
|
||||||
|
```
|
||||||
|
|
||||||
### Random integer in range
|
### Random integer in range
|
||||||
|
|
||||||
Use `Math.random()` to generate a random number and map it to the desired range, using `Math.floor()` to make it an integer.
|
Use `Math.random()` to generate a random number and map it to the desired range, using `Math.floor()` to make it an integer.
|
||||||
|
|||||||
17
snippets/promisify.md
Normal file
17
snippets/promisify.md
Normal file
@ -0,0 +1,17 @@
|
|||||||
|
### Promisify
|
||||||
|
|
||||||
|
Use currying to return a function returning a `Promise` that calls the original function.
|
||||||
|
Use the `...rest` operator to pass in all the parameters.
|
||||||
|
|
||||||
|
*In Node 8+, you can use [`util.promisify`](https://nodejs.org/api/util.html#util_util_promisify_original)*
|
||||||
|
|
||||||
|
```js
|
||||||
|
const promisify = func =>
|
||||||
|
(...args) =>
|
||||||
|
new Promise((resolve, reject) =>
|
||||||
|
func(...args, (err, result) =>
|
||||||
|
err ? reject(err) : resolve(result))
|
||||||
|
);
|
||||||
|
// const delay = promisify((d, cb) => setTimeout(cb, d))
|
||||||
|
// delay(2000).then(() => console.log('Hi!')) -> Promise resolves after 2s
|
||||||
|
```
|
||||||
Reference in New Issue
Block a user