Skip to content

Commit

Permalink
Add support for thenables
Browse files Browse the repository at this point in the history
Closes GH-12.
Closes GH-13.

Co-authored-by: Rafael Mestre <rafaelmestre@outlook.com>
Co-authored-by: Titus Wormer <tituswormer@gmail.com>
  • Loading branch information
wooorm and rlmestre committed Feb 5, 2024
1 parent 48aed67 commit b31fcf3
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 1 deletion.
2 changes: 1 addition & 1 deletion lib/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -173,7 +173,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
42 changes: 42 additions & 0 deletions test.js
Original file line number Diff line number Diff line change
Expand Up @@ -267,6 +267,48 @@ test('promise middleware', async function (t) {
})
}
)

await t.test('should support thenables', async function () {
// See: <https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise#thenables>
let calls = 0

/** @type {Promise<unknown>} */
const promise = new Promise(function (resolve) {
trough()
.use(function () {
return {
/**
* @param {(value: unknown) => void} resolve
*/
// eslint-disable-next-line unicorn/no-thenable
then(resolve) {
setTimeout(function () {
resolve(42)
})
}
}
})
.run(
/**
* @param {unknown} [error]
* @param {unknown} [value]
* @returns {undefined}
*/
function (error, value) {
assert.equal(error, null)
assert.equal(value, 42)
calls++
resolve(undefined)
}
)
})

assert.equal(calls, 0)

await promise

assert.equal(calls, 1)
})
})

test('asynchronous middleware', async function (t) {
Expand Down

0 comments on commit b31fcf3

Please sign in to comment.