Skip to content
Permalink
Browse files
Add option to support non-error-first APIs (#42)
Fixes #31
  • Loading branch information
sindresorhus committed May 27, 2017
1 parent be9a0eb commit fad7b3d2dfa4ad90e304107bd500799e07be538b
Showing 3 changed files with 59 additions and 16 deletions.
@@ -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 => {
@@ -105,6 +105,13 @@ if (promiseFn()) {
}
```

##### errorFirst

Type: `boolean`<br>
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`
19 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
})('🦄', '🌈'), ['🦄', '🌈']);
});

0 comments on commit fad7b3d

Please sign in to comment.