/\*
\* 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(...);
> async function foo() { return "hello"; } foo().then(console.log); console.log("after")
after hello
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?
I’m thinking about new projects rather than converting existing projects.
One benefit I can see to .mjs is that if all extensions are .mjs it’s clear what type of project it is without the need to open up package.json.
About new projects, I'd have to read more about this new extension, for some reason it feels like a temporary solution that'll just get merged to the normal js extension in a future release.
From what I’ve read though, there doesn’t appear to be much of a plan apart from the current solution.
My initial reaction is that I want to keep all my files with .js extension.
One thing that could potentially be problematic is for files that need to run in the browser and on the server.
Really curious to see where the community’s tea leaves settle. My guess is that people will eventually just start using the new extension.
Deno basically does this with the Deno standard library, e.g. https://deno.land/[email protected], 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.