Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/kritollm/cb-topromise-wrapper
Easily convert a function that takes a callback to return a promise instead.
https://github.com/kritollm/cb-topromise-wrapper
async callback convert promise
Last synced: about 1 month ago
JSON representation
Easily convert a function that takes a callback to return a promise instead.
- Host: GitHub
- URL: https://github.com/kritollm/cb-topromise-wrapper
- Owner: kritollm
- License: mit
- Created: 2017-03-31T08:58:47.000Z (over 7 years ago)
- Default Branch: master
- Last Pushed: 2017-04-02T21:52:53.000Z (over 7 years ago)
- Last Synced: 2024-10-10T09:19:48.453Z (about 1 month ago)
- Topics: async, callback, convert, promise
- Language: JavaScript
- Size: 10.7 KB
- Stars: 1
- Watchers: 2
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# cb-topromise-wrapper
## Description
Easily turn a function that takes a callback to instead returning a promise.## Requirements
The callback must be the last parameter and have node style parameters.
```javascript
function cb(error, result){
if(error){
// handle error
} else{
// handle result
}
}
```
## Usage
```bash
$ npm install -S cb-topromise-wrapper
``````javascript
// var promiseWrapper = require(cb-topromise-wrapper).promiseWrapper;
import { promiseWrapper } from 'cb-topromise-wrapper';
const fs = require('fs');const readFile = promiseWrapper(fs.readFile);
readFile('JsonData/yourfile.json', 'utf8')
.then(console.log.bind(console))
.catch(console.error.bind(console));```
## If you like node style result.
```javascript
// var promiseWrapper = require(cb-topromise-wrapper).promiseWrapper;
import { promiseWrapper } from 'cb-topromise-wrapper';
const fs = require('fs');function resultHandler({error, result}){
if(error){
// handle error
} else{
// handle result
}
}
const readFile = promiseWrapper(fs.readFile);
readFile('JsonData/yourfile.json', 'utf8')
.then(result => resultHandler({error: null, result}))
.catch(error => resultHandler({error, result: null}));
```## Gotcha
If you wants to wrap a method you must replace it or bind it.If the method is in the prototype and you want's every new instance to have the
wrapped method you must remember to replace the prototype method.You can also bind the method to the object.
```javascript
// var promiseWrapper = require(cb-topromise-wrapper).promiseWrapper;
import { promiseWrapper } from 'cb-topromise-wrapper';
import { createBlobService } from 'azure-storage';const blobService = createBlobService();
const createBlockBlobFromText = promiseWrapper(blobService.createBlockBlobFromText.bind(blobService));
```