simple-callback-promisify

1.0.1 • Public • Published

Wrap callback to promise

this package now does assume callback in this specific format:

(err, data) => {}

or you can set complex to true in options, then all the params for the callback will be available as an array in 'then'

func(..., (param1, param2, param3, ...) => {})

will become

func(...).then(([param1, param2, param3, ...]) => {})

How to use

Call this module with you function that needs callback, and it will return a promise

Example

the followings are equivalent

const readFile = fs.readFile('dist', (err, data) => {
  if (!err) {
    console.log('successfully read file:', data);
    return;
  }
  console.log('error from fs read file:', err);
})
const callbackToPromise = require('simple-callback-promisify');
const readFilePromise = callbackToPromise(fs.readFile);
readFilePromise.then(
  data => console.log('successfully read file:', data);
).catch(
  err => console.log('error from fs read file:', err);
)

with complex set to true

const callbackToPromise = require('simple-callback-promisify');
const readFilePromise = callbackToPromise(fs.readFile, { complex: true });
readFilePromise.then(
  ([err, data]) => {
    if (err) {
      throw err;
    }
    console.log('successfully read file:', data);
  }
)

you can also use async/await

const callbackToPromise = require('simple-callback-promisify');
const readFilePromise = callbackToPromise(fs.readFile);
try {
  const data = await readFilePromise('dist');
  console.log('successfully read file:', data);
} catch (err) {
  console.log('error from fs read file:', err);
}

Readme

Keywords

Package Sidebar

Install

npm i simple-callback-promisify

Weekly Downloads

0

Version

1.0.1

License

MIT

Unpacked Size

6.72 kB

Total Files

7

Last publish

Collaborators

  • will32