This content originally appeared on Stefan Judis Web Development and was authored by Stefan Judis
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. ?
FYI: Node.js modules support top-level await.
// File: index.mjs
const sleep = (time) => {
return new Promise((resolve) => {
setTimeout(resolve, time);
});
}
// do something
await sleep(5000);
// do something else
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.
import {
setTimeout,
} from 'timers/promises';
// do something
await setTimeout(5000);
// do something else
Less code is always better code! ?
Reply to Stefan
This content originally appeared on Stefan Judis Web Development and was authored by Stefan Judis

Stefan Judis | Sciencx (2021-08-25T22:00:00+00:00) Promises-based timer functions are supported in Node.js 16 (#snippet). Retrieved from https://www.scien.cx/2021/08/25/promises-based-timer-functions-are-supported-in-node-js-16-snippet/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.