create-promise-callback

1.0.0 • Public • Published

create-promise-callback

NPM version Build Status

Make asynchronous methods support both Promise and callback.

Install

$ yarn add create-promise-callback

Usage

import createPromiseCallback from 'create-promise-callback';

function get(key, fn) {
  fn = fn || createPromiseCallback();

  RedisClient
    .get(key)
    .then((err, res) => {
      if(err) return fn(err);
      fn(null, res);
    })

  return fn.promise;
}

// callback
get('yourkey', (err, res) => {
  console.log(res);
})

// promise
get('yourkey')
  .then(res => {
    console.log(res);
  })
  .catch(err => {
    console.log(err);
  })

// also resolve with multi arguments
function multiArgsFunc(fn) {
  fn = fn || createPromiseCallback();

  yourFunc()
    .then((err, arg1, arg2) => {
      if(err) return fn(err);
      fn(null, arg1, arg2);
    })

  return fn.promise;
}

multiArgsFunc()
  .then((arg1, arg2) => {
    // ...
  })

Use your preferred Promise library

set global.Promise to your preferred Promise libaray like bluebird.

global.Promise = require('bluebird')

License

MIT

Readme

Keywords

Package Sidebar

Install

npm i create-promise-callback

Weekly Downloads

1

Version

1.0.0

License

MIT

Unpacked Size

125 kB

Total Files

11

Last publish

Collaborators

  • yangteng