4
Recently, in the version V16.0.0 of Node.js, added the Promises Timers API, and from what I understand, it’s about alter the behavior of standard timers (setTimeout
, setImmediate
, etc...). These timers return objects NodeJS.Timeout
, in this way:
If made a console.log(setTimeout(() => {}, 0))
, we have:
Timeout {
_idleTimeout: 1000,
_idlePrev: [TimersList],
_idleNext: [TimersList],
_idleStart: 34,
_onTimeout: [Function (anonymous)],
_timerArgs: undefined,
_repeat: null,
_destroyed: false,
[Symbol(refed)]: true,
[Symbol(kHasPrimitive)]: false,
[Symbol(asyncId)]: 7,
[Symbol(triggerId)]: 0
}
Now, thanks to this API, the new functions return an object Promise
.
In this example (adapted by me) from the documentation, we have:
import { setTimeout } from 'timers/promises';
const twoSeconds = 2_000;
const res = await setTimeout(twoSeconds, 'result');
// Exibe a string "result" depois de 2 segundos.
console.log(res);
This function above is much simpler and takes less code to build and understand. Note that this function returns a promise, which allows the use of the await
. This new API "kind of" makes a "promissification" of the timer setTimeout
behind the scenes.
In the example above, if I make a console.log(setTimeout(() => {}, 0))
, I’ll have at the terminal:
Promise { <pending> }
I wanted to know:
- If that "promissification" of timers is the main purpose of this new implementation.
- She solves what problems?
This API was inserted in version v15.0.0 as experimental and was stabilized in version V16.0.0 of Node.js.
As most of the other Node Apis are promise-based, I believe they have created this new version of the timers to make it easier to use with these other Apis. Remembering that the "standard" Node timers API was no longer standard - but a transposition of the implementation that exists in browsers, part of the DOM API (I think).
– bfavaretto
@bfavaretto Yes! would be the API of
window
in the case?setTimeout()
is similar to APIwindow.setTimeout
of browsers.– Cmte Cardeal
Yeah, that’s the one I’m talking about.
– bfavaretto