From e7c51454b0de0a6b33c15a4d77006a17ced4eeff 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 2b6af6f66f4..8abcdcb5cb6 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])