From fad7b3d2dfa4ad90e304107bd500799e07be538b Mon Sep 17 00:00:00 2001 From: Sindre Sorhus Date: Sat, 27 May 2017 20:45:42 +0700 Subject: [PATCH] Add option to support non-error-first APIs (#42) Fixes #31 --- index.js | 49 +++++++++++++++++++++++++++++++++---------------- readme.md | 7 +++++++ test.js | 19 +++++++++++++++++++ 3 files changed, 59 insertions(+), 16 deletions(-) diff --git a/index.js b/index.js index 35513b7..de449e1 100644 --- a/index.js +++ b/index.js @@ -9,26 +9,42 @@ const processFn = (fn, opts) => function () { } return new P((resolve, reject) => { - args.push(function (err, result) { - if (opts.multiArgs) { - const results = new Array(arguments.length - 1); + if (opts.errorFirst) { + args.push(function (err, result) { + if (opts.multiArgs) { + const results = new Array(arguments.length - 1); - for (let i = 1; i < arguments.length; i++) { - results[i - 1] = arguments[i]; - } + for (let i = 1; i < arguments.length; i++) { + results[i - 1] = arguments[i]; + } - if (err) { - results.unshift(err); - reject(results); + if (err) { + results.unshift(err); + reject(results); + } else { + resolve(results); + } + } else if (err) { + reject(err); } else { + resolve(result); + } + }); + } else { + args.push(function (result) { + if (opts.multiArgs) { + const results = new Array(arguments.length - 1); + + for (let i = 0; i < arguments.length; i++) { + results[i] = arguments[i]; + } + resolve(results); + } else { + resolve(result); } - } else if (err) { - reject(err); - } else { - resolve(result); - } - }); + }); + } fn.apply(this, args); }); @@ -37,7 +53,8 @@ const processFn = (fn, opts) => function () { module.exports = (obj, opts) => { opts = Object.assign({ exclude: [/.+(Sync|Stream)$/], - promiseModule: Promise + promiseModule: Promise, + errorFirst: true }, opts); const filter = key => { diff --git a/readme.md b/readme.md index a1ce309..4118ec5 100644 --- a/readme.md +++ b/readme.md @@ -105,6 +105,13 @@ if (promiseFn()) { } ``` +##### errorFirst + +Type: `boolean`
+Default: `true` + +Whether the callback has an error as the first argument. You'll want to set this to `false` if you're dealing with an API that doesn't have an error as the first argument, like `fs.exists()`, some browser APIs, Chrome Extension APIs, etc. + ##### promiseModule Type: `Function` diff --git a/test.js b/test.js index 298a51f..925ba8b 100644 --- a/test.js +++ b/test.js @@ -123,3 +123,22 @@ test('module support — function modules exclusion', t => { t.is(typeof pModule.meow().then, 'function'); t.not(typeof pModule(() => {}).then, 'function'); }); + +test('`errorFirst` option', async t => { + const fixture = (foo, cb) => { + cb(foo); + }; + + t.is(await m(fixture, {errorFirst: false})('🦄'), '🦄'); +}); + +test('`errorFirst` option and `multiArgs`', async t => { + const fixture = (foo, bar, cb) => { + cb(foo, bar); + }; + + t.deepEqual(await m(fixture, { + errorFirst: false, + multiArgs: true + })('🦄', '🌈'), ['🦄', '🌈']); +});