by dfabulich · 5y ago · 0 comments
import { setTimeout } from 'timers/promises';
await setTimeout(1000);
console.log("awake");
(But note that you'll have to activate ESM mode to write this script, e.g. by writing it in a `.mjs` file instead of a `.js` file or by adding a setting to package.json.) https://redfin.engineering/node-modules-at-war-why-commonjs-... /\*
\* A sleep function that returns a promise.
\*
\* @example
\* Sleep for 100ms
\* ```
\* await wait(100);
\* ```
\*/
export async function wait(ms: number) {
return new Promise(resolve => {
setTimeout(resolve, ms);
});
}const wait = require('util').promisify(setTimeout)
[1] https://nodejs.org/dist/latest-v16.x/docs/api/util.html#util...
I prefer
async function foo() { return await new Promise(...) }
as opposed to
function foo() { return new Promise(...) }
They're the same thing for the most part but the latter I have to potentially dig deeper into the function to confirm it returns a promise compared to the former.
For documentation purposes, I recommend block-commenting the `async`:
const foo = /async/ () => new Promise(...);
It doesn't need to be that tricky.
My initial thoughts were “urgh I just want to have .js files in my projects” but I’m wondering if I’ll warm to them given that they make things a lot easier.
Are people eventually just all going to use .mjs files for everything?
Deno basically does this with the Deno standard library, e.g. https://deno.land/std@0.93.0, and I agree that I think it's the right approach.
There is nothing "special" about wrapping setTimeout as a Promise, indeed pretty much everyone has done it at some point, so would be nice if there was a single, blessed standard version that I could just add as @node/standard in my package.json as long as I was on any supported Node version.
I prefer my batteries included. Also importing from "timers/promises" isn't a global namespace.
The most common stuff I like to be part of the standard lib, either node or javascript, but it works fairly well now I guess so no biggie.
That said, I'll probably spend more time searching the node docs for how to import/use it than just implementing it myself.
OTOH I use promisified timer in almost all of my web scraping scripts, to reduce the load on the server, so I'm glad I'll be able to drop this thing from my utility library.