Skip to content

Commit

Permalink
Add option to support non-error-first APIs (#42)
Browse files Browse the repository at this point in the history
Fixes #31
  • Loading branch information
sindresorhus authored May 27, 2017
1 parent be9a0eb commit fad7b3d
Show file tree
Hide file tree
Showing 3 changed files with 59 additions and 16 deletions.
49 changes: 33 additions & 16 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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);
});
Expand All @@ -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 => {
Expand Down
7 changes: 7 additions & 0 deletions readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`
Expand Down
19 changes: 19 additions & 0 deletions test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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.