From 42ed00bb8fb659dc6868e21f65734ecf12aa57e7 Mon Sep 17 00:00:00 2001 From: James Talmage Date: Sun, 12 Jun 2016 03:10:29 -0400 Subject: [PATCH 1/2] allow member function access --- index.js | 4 ++++ optimization-test.js | 2 +- test.js | 16 ++++++++++++++++ 3 files changed, 21 insertions(+), 1 deletion(-) diff --git a/index.js b/index.js index 58c28b3..dfb3513 100644 --- a/index.js +++ b/index.js @@ -37,6 +37,10 @@ var pify = module.exports = function (obj, P, opts) { P = Promise; } + if (typeof opts === 'string') { + return processFn(obj[opts], P, {}).bind(obj); + } + opts = opts || {}; var exclude = opts.exclude || [/.+Sync$/]; diff --git a/optimization-test.js b/optimization-test.js index c883b7a..020993d 100644 --- a/optimization-test.js +++ b/optimization-test.js @@ -1,4 +1,4 @@ -/* eslint-disable no-fallthrough */ +/* eslint-disable no-fallthrough, xo/no-process-exit*/ 'use strict'; var assert = require('assert'); var Promise = require('pinkie-promise'); diff --git a/test.js b/test.js index 6b67139..38e206b 100644 --- a/test.js +++ b/test.js @@ -27,6 +27,16 @@ const fixtureModule = { method3: fixture5 }; +class Concat { + constructor(a) { + this.a = a; + } + + b(b, cb) { + setImmediate(() => cb(null, this.a + b)); + } +} + test('main', async t => { t.is(typeof fn(fixture)().then, 'function'); t.is(await fn(fixture)(), 'unicorn'); @@ -44,6 +54,12 @@ test('multiArgs option', async t => { t.deepEqual(await fn(fixture3, {multiArgs: true})(), ['unicorn', 'rainbow']); }); +test('string option returns promisified thunk for member function', async t => { + const concat = new Concat('foo'); + + t.is(await fn(concat, 'b')('bar'), 'foobar'); +}); + test('wrap core method', async t => { t.is(JSON.parse(await fn(fs.readFile)('package.json')).name, 'pify'); }); From 2a58e44e2abfa00b5c2e3d2874d769e013afe0a6 Mon Sep 17 00:00:00 2001 From: James Talmage Date: Sun, 12 Jun 2016 03:18:26 -0400 Subject: [PATCH 2/2] documentation --- readme.md | 20 +++++++++++++++++++- 1 file changed, 19 insertions(+), 1 deletion(-) diff --git a/readme.md b/readme.md index b0854b6..c83b7ed 100644 --- a/readme.md +++ b/readme.md @@ -34,7 +34,7 @@ pify(fs).readFile('package.json', 'utf8').then(data => { ## API -### pify(input, [promiseModule], [options]) +### pify(input, [promiseModule], [methodName | options]) Returns a promise wrapped version of the supplied function or module. @@ -52,6 +52,24 @@ Custom promise module to use instead of the native one. Check out [`pinkie-promise`](https://github.com/floatdrop/pinkie-promise) if you need a tiny promise polyfill. +#### methodName + +Type: `string` + +Specify a specific member function of `input` to promisify: + +```js +var x = { + a: 'foo', + b: function (b, cb) { + cb(null, this.a + b); + } +}; + +pify(x, 'b')('bar') +//=> Promise for "foobar" +``` + #### options ##### multiArgs