add timeout support for async function
$ pnpm add promise.timeout
AbortController
, Node.js has builtin global since v15var ptimeout = require('promise.timeout')
ptimeout(fn, timeout)
fn
the async functiontimeout
in msvar ptimeout = require('promise.timeout')
// a function will cost 20ms
function test() {
return new Promise(function (resolve, reject) {
setTimeout(function () {
resolve(20)
}, 20)
})
}
var test10 = ptimeout(test, 10)
var test50 = ptimeout(test, 50)
// 10 timeout
try {
await test10()
} catch (e) {
e.should.be.ok()
e.should.be.instanceof(ptimeout.TimeoutError)
e.message.should.match(/timeout/)
e.timeout.should.equal(10)
}
// 50 ok
var _50 = await test50()
_50.should.be.ok()
_50.should.equal(20)
ptimeout will provide an extra runtime argument signal: AbortSignal
, you can use the signal to register abort action.
when timeout reached, the abort action will be executed
var ptimeout = require('promise.timeout')
// a function will cost 20ms
function test(signal) {
return new Promise(function (resolve, reject) {
var timer = setTimeout(function () {
resolve(20)
}, 20)
// clean up
signal.addEventListener('abort', () => {
clearTimeout(timer)
})
})
}
var test10 = ptimeout(test, 10)
try {
await test10()
} catch (e) {
e.should.ok()
}
AbortController
AbortController
& AbortSignal
if not provided nativlyonCancel
like the AbortControllerwith AbortController
you need to
function normalFn(a, r, g, s, controller: AbortController) {
controller.signal.addEventListener('abort', () => {
// cancel operations that starts in `normalFn` body
})
}
ptimeout
will call the controller.abort()
if any timeout exceedsonCancel
, you provide a cancel operation to ptimeout, ptimeout will call thatThat's the same, and I don't want to depend on an extra package abort-controller
the MIT License http://magicdawn.mit-license.org