dparlevliet / node.bittrex.api

Node Bittrex API is an asynchronous node.js library for the Bittrex API, the data can be received either via GET request or Stream.
MIT License
253 stars 100 forks source link

Improvement request: Cannot promisify easily as standard node convention not supported #77

Closed rvenugopal closed 6 years ago

rvenugopal commented 6 years ago

I would like to use const bittrex = blueBird.promisifyAll(require('node.bittrex.api')); However, as the library does not follow standard node convention, I am not able to.

The target methods are assumed to conform to node.js callback convention of accepting a callback as last argument and calling that callback with error as the first argument and success value on the second argument. http://bluebirdjs.com/docs/api/promise.promisifyall.html#promisification

A work around I am using to promisify individual methods on ad-hoc basis using the below method but is not ideal (i am using

function wrapWithPromise(fn) {
  return function(...args) {
    return new Promise( (resolve, reject) => fn(resolve, reject, ...args) );
  }
}

const getmarketsummaries = wrapWithPromise(bittrex.getmarketsummaries)
rvenugopal commented 6 years ago

For anyone else who might be interested, here is a function which can help promisify this library.

function promisifyAll(input) {
  function promisifier(method) {
    return function promisified(...args) {
      return new Promise((resolve) => {
        args.push(resolve);
        const self = this;
        method.apply(self, args); 
      });
    };
  }

  function promisifyAll(obj) {
    for (const key in obj) {
      if (typeof obj[key] === 'function' && key.indexOf('Async') === -1) {
        obj[key + 'Async'] = promisifier(obj[key])
      }
    }
  }

  promisifyAll(input);
  return input
}

const bittrexPromisified = promisifyAll(require('node.bittrex.api'));

bittrexPromisified.getmarketsummariesAsync()
    .then((data) => {
      console.log('Results:', data.result.length)
    })
dparlevliet commented 6 years ago

There is an option for this already. See inverse_callback_arguments