Hacker News new | ask | show | jobs
by wereHamster 527 days ago
Unrelated to the topic in the article…

    await new Promise(resolve => setTimeout(resolve, 500));
In Node.js context, it's easier to:

    import { setTimeout } from "node:timers/promises";
    await setTimeout(500);
2 comments

I haven't used that once since I found out that it exists.

I just don't see the point. It doesn't work in the browser and it shadows global.setTimeout which is confusing. Meanwhile the idiom works everywhere.

You can alias it if you're worried about shadowing.

    import { setTimeout as loiter } from "node:timers/promises";
    await loiter(500);
Sure, and that competes with a universal idiom.

To me it's kinda like adding a shallowClone(old) helper instead of writing const obj = { ...old }.

But no point in arguing about it forever.

Is that easier? The first snippet is shorter and works on any runtime.
In the context of Node.js, where op said, yes it is easier. But it's a new thing and most people don't realize timers in Node are awaitable yet, so the other way is less about "works everywhere" and more "this is just what I know"
I guess most Node.js developers also don't realize that there's "node:fs/promises" so you don't have to use callbacks or manually wrap functions from "node:fs" with util.promisify(). Doesn't mean need to stick with old patterns forever.

When I said 'in the context of Node.js' I meant if you are in a JS module where you already import other node: modules, ie. when it's clear that code runs in a Node.js runtime and not in a browser. Of course when you are writing code that's supposed to be portable, don't use it. Or don't use setTimeout at all because it's not guaranteed to be available in all runtimes - it's not part of the ECMA-262 language specification after all.