Merge pull request #64 from DanielRamosAcosta/add-promisify-snippet

Add promisify snippet
This commit is contained in:
Angelos Chalaris
2017-12-13 14:18:14 +02:00
committed by GitHub
2 changed files with 36 additions and 0 deletions

17
snippets/promisify.md Normal file
View 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
```