Skip to content

Commit

Permalink
Handle Promises via duck typing
Browse files Browse the repository at this point in the history
  • Loading branch information
rlmestre committed Feb 2, 2024
1 parent 787d92e commit 8e66e1f
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 1 deletion.
2 changes: 1 addition & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,7 @@ export function wrap(middleware, callback) {
}

if (!fnExpectsCallback) {
if (result instanceof Promise) {
if (result && result.then && typeof result.then === 'function') {
result.then(then, done)
} else if (result instanceof Error) {
done(result)
Expand Down
41 changes: 41 additions & 0 deletions test.js
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,47 @@ test('promise middleware', async function () {
})
})

await new Promise((resolve) => {
trough()
.use((/** @type {string} */ value) => {
assert.equal(value, 'some', 'should pass values to `fn`s')

/**
* @callback resolveCallback
* @param {string} value
*/
return {
then: (/** @type {resolveCallback} */ resolve) => {
resolve(value + 'thing')
}
}
})
.run('some', (/** @type {void} */ error, /** @type {string} */ value) => {
assert.ifError(error)
assert.equal(value, 'something', 'should pass values to `done`')
resolve(undefined)
})
})

await new Promise((resolve) => {
trough()
.use((/** @type {string} */ value) => {
assert.equal(value, 'some', 'should pass values to `fn`s')

return {
then: 'something'
}
})
.run(
'some',
(/** @type {void} */ error, /** @type {{ then: string }} */ value) => {
assert.ifError(error)
assert.equal(value.then, 'something', 'should pass values to `done`')
resolve(undefined)
}
)
})

await new Promise((resolve) => {
trough()
.use((/** @type {string} */ value) => {
Expand Down

0 comments on commit 8e66e1f

Please sign in to comment.