From 2c904cc176e196c962424f9cced076c1d63d988c Mon Sep 17 00:00:00 2001 From: Anna Henningsen Date: Fri, 14 Apr 2017 21:42:47 +0200 Subject: [PATCH] timers: add promisify support Add support for `util.promisify(setTimeout)` and `util.promisify(setImmediate)` as a proof-of-concept implementation. `clearTimeout()` and `clearImmediate()` do not work on those Promises. Includes documentation and tests. PR-URL: https://github.com/nodejs/node/pull/12442 Reviewed-By: Benjamin Gruenbaum Reviewed-By: Matteo Collina Reviewed-By: James M Snell Reviewed-By: Myles Borins Reviewed-By: Evan Lucas Reviewed-By: William Kapke Reviewed-By: Timothy Gu Reviewed-By: Teddy Katz --- doc/api/timers.md | 38 ++++++++++++++++++++++ lib/timers.js | 26 +++++++++++++-- test/parallel/test-timers-promisified.js | 40 ++++++++++++++++++++++++ 3 files changed, 102 insertions(+), 2 deletions(-) create mode 100644 test/parallel/test-timers-promisified.js diff --git a/doc/api/timers.md b/doc/api/timers.md index 2b6af6f66f41fe..8abcdcb5cb6890 100644 --- a/doc/api/timers.md +++ b/doc/api/timers.md @@ -85,6 +85,27 @@ next event loop iteration. If `callback` is not a function, a [`TypeError`][] will be thrown. +*Note*: This method has a custom variant for promises that is available using +[`util.promisify()`][]: + +```js +const util = require('util'); +const setImmediatePromise = util.promisify(setImmediate); + +setImmediatePromise('foobar').then((value) => { + // value === 'foobar' (passing values is optional) + // This is executed after all I/O callbacks. +}); + +// or with async function +async function timerExample() { + console.log('Before I/O callbacks'); + await setImmediatePromise(); + console.log('After I/O callbacks'); +} +timerExample(); +``` + ### setInterval(callback, delay[, ...args])