What is the purpose of the 'node:timers/promises' module, and how does it simplify working with delays in async code?
Short answer
node:timers/promises provides promise-returning versions of setTimeout, setImmediate, and setInterval, letting them be used directly with await instead of needing to be manually wrapped in a Promise constructor -- this removes a very common piece of boilerplate that used to…
Advertisement
AModel answer
node:timers/promises provides promise-returning versions of setTimeout, setImmediate, and setInterval, letting them be used directly with await instead of needing to be manually wrapped in a Promise constructor -- this removes a very common piece of boilerplate that used to appear at the top of countless Node.js files.
const { setTimeout: sleep } = require('node:timers/promises');
async function retryLater() {
console.log('Waiting 2 seconds...');
await sleep(2000);
console.log('Done waiting.');
}Real-world example
A rate-limited API client uses timers/promises' setTimeout directly with await to pause between retries, replacing a small hand-written 'function delay(ms) { return new Promise(resolve => setTimeout(resolve, ms)); }' helper that used to be copy-pasted into nearly every project.
Likely follow-ups
- How does timers/promises' setInterval as an async iterator differ from the traditional callback-based setInterval?
- Can these promise-based timers be cancelled, and if so how?
Related topics