diff options
author | James M Snell <jasnell@gmail.com> | 2020-06-11 00:14:23 +0300 |
---|---|---|
committer | James M Snell <jasnell@gmail.com> | 2020-06-18 21:40:10 +0300 |
commit | bfbdc84738e87e0aa067b067e4b68cabbe75a793 (patch) | |
tree | 5ec8c810e16912deb3cc36eb948553efe8fcffca /doc/api/timers.md | |
parent | 0ef6956225bbf4ff9e06a4e87cccb3b5053a841b (diff) |
timers: allow promisified timeouts/immediates to be canceled
Using the new experimental AbortController...
Signed-off-by: James M Snell <jasnell@gmail.com>
PR-URL: https://github.com/nodejs/node/pull/33833
Reviewed-By: Anna Henningsen <anna@addaleax.net>
Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
Reviewed-By: Gus Caplan <me@gus.host>
Diffstat (limited to 'doc/api/timers.md')
-rw-r--r-- | doc/api/timers.md | 44 |
1 files changed, 42 insertions, 2 deletions
diff --git a/doc/api/timers.md b/doc/api/timers.md index a312022791f..3dcd1f4e475 100644 --- a/doc/api/timers.md +++ b/doc/api/timers.md @@ -232,8 +232,47 @@ The [`setImmediate()`][], [`setInterval()`][], and [`setTimeout()`][] methods each return objects that represent the scheduled timers. These can be used to cancel the timer and prevent it from triggering. -It is not possible to cancel timers that were created using the promisified -variants of [`setImmediate()`][], [`setTimeout()`][]. +For the promisified variants of [`setImmediate()`][] and [`setTimeout()`][], +an [`AbortController`][] may be used to cancel the timer. When canceled, the +returned Promises will be rejected with an `'AbortError'`. + +For `setImmediate()`: + +```js +const util = require('util'); +const setImmediatePromise = util.promisify(setImmediate); + +const ac = new AbortController(); +const signal = ac.signal; + +setImmediatePromise('foobar', { signal }) + .then(console.log) + .catch((err) => { + if (err.message === 'AbortError') + console.log('The immediate was aborted'); + }); + +ac.abort(); +``` + +For `setTimeout()`: + +```js +const util = require('util'); +const setTimeoutPromise = util.promisify(setTimeout); + +const ac = new AbortController(); +const signal = ac.signal; + +setTimeoutPromise(1000, 'foobar', { signal }) + .then(console.log) + .catch((err) => { + if (err.message === 'AbortError') + console.log('The timeout was aborted'); + }); + +ac.abort(); +``` ### `clearImmediate(immediate)` <!-- YAML @@ -264,6 +303,7 @@ added: v0.0.1 Cancels a `Timeout` object created by [`setTimeout()`][]. [Event Loop]: https://nodejs.org/en/docs/guides/event-loop-timers-and-nexttick/#setimmediate-vs-settimeout +[`AbortController`]: globals.html#globals_class_abortcontroller [`TypeError`]: errors.html#errors_class_typeerror [`clearImmediate()`]: timers.html#timers_clearimmediate_immediate [`clearInterval()`]: timers.html#timers_clearinterval_timeout |