Skip to content

Commit

Permalink
Fix bug with optional parameter promise functions
Browse files Browse the repository at this point in the history
Previously, we didn't remove the callback parameter from the
arguments when calling a promise function, this confused functions
with optional parameters, since the last parameter would be the
callback function.
  • Loading branch information
RyanZim committed Feb 19, 2020
1 parent 4057d40 commit 1df636f
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 1 deletion.
6 changes: 5 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,10 @@ exports.fromPromise = function (fn) {
return Object.defineProperty(function () {
const cb = arguments[arguments.length - 1]
if (typeof cb !== 'function') return fn.apply(this, arguments)
else fn.apply(this, arguments).then(r => cb(null, r), cb)
else {
delete arguments[arguments.length - 1]
arguments.length--
fn.apply(this, arguments).then(r => cb(null, r), cb)
}
}, 'name', { value: fn.name })
}
23 changes: 23 additions & 0 deletions test/from-promise.js
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,29 @@ test('promise function works with promises', t => {
.catch(t.end)
})

test('promise function optional param works with callbacks', t => {
t.plan(4)
fn.call({a: 'a'}, 1, (err, arr) => {
t.ifError(err, 'should not error')
t.is(arr[0].a, 'a')
t.is(arr[1], 1)
t.is(arr[2], undefined)
t.end()
})
})

test('promise function optional param works with promises', t => {
t.plan(3)
fn.call({a: 'a'}, 1)
.then(arr => {
t.is(arr[0].a, 'a')
t.is(arr[1], 1)
t.is(arr[2], undefined)
t.end()
})
.catch(t.end)
})

test('promise function error works with callbacks', t => {
t.plan(2)
errFn(err => {
Expand Down

0 comments on commit 1df636f

Please sign in to comment.