Promises-based timer functions are supported in Node.js 16
Written by Stefan Judis
- Published at
- Updated at
- Reading time
- 1min
When writing Node.js automation/build scripts, I occasionally need "sleep" functionality to wait for other tasks to finish. It's not great to implement "sleeps and waits", but sometimes there's no other way than waiting for another system to finish what it's doing.
I often use the following snippet in a Node.js module script. ๐
// File: index.mjs
const sleep = (time) => {
return new Promise((resolve) => {
setTimeout(resolve, time);
});
}
// do something
await sleep(5000);
// do something else
Node.js modules support top-level await these days.
There's nothing particularly wrong with this approach, but I'm very pleased to see that promises-based timer functions are available in Node.js 16 via timers/promises
now.
// File: index.mjs
import {
setTimeout,
} from 'timers/promises';
// do something
await setTimeout(5000);
// do something else
Less code is always better code! ๐
If you enjoyed this article...
Join 5.5k readers and learn something new every week with Web Weekly.
Reply to this post and share your thoughts via good old email.