README
promise.timeout
add timeout support for async function
Install
$ npm i -S promise.timeout
Note
this is target ES5 environment.
API
var ptimeout = require('promise.timeout')
ptimeout(fn, timeout, cancel)
fn
the async functiontimeout
in mscancel
Boolean, whether support onCancel
var 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)
onCancel
- pass
cancel = true
toptimeout(fn, ms, cancel)
- use
onCancel
para to register clean callback
var ptimeout = require('promise.timeout')
// a function will cost 20ms
function test(onCancel) {
return new Promise(function(resolve, reject) {
var timer = setTimeout(function() {
resolve(20)
}, 20)
// custom clean
onCancel &&
onCancel(() => {
clearTimeout(timer)
})
})
}
var test10 = ptimeout(test, 10, true) // enable cancel
try {
await test10()
} catch (e) {
e.should.ok()
}
FAQ
Q: Why onCancel
onCancel
like the AbortController
A: Think with AbortController
you need to
function normalFn(a, r, g, s, controller: AbortController) {
controller.signal.addEventListener('abort', () => {
// cancel operations that starts in `normalFn` body
})
}
- and
ptimeout
will call thecontroller.abort()
if any timeout exceeds - and with
onCancel
, you provide a cancel operation to ptimeout, ptimeout will call that
That's the same, and I don't want to depend on an extra package abort-controller
See Also
Changelog
License
the MIT License http://magicdawn.mit-license.org