6 ms·
Unrelated to the topic in the article… await new Promise(resolve => setTimeout(resolve, 500)); In Node.js context, it's easier to: import { setTimeou
by wereHamster 2y 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);
- treve 2y agoIs that easier? The first snippet is shorter and works on any runtime.
- joshmanders 2y agoIn 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"
- wereHamster 2y agoI 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.
- hombre_fatal 2y agoI 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.
- joshmanders 2y agoYou can alias it if you're worried about shadowing. import { setTimeout as loiter } from "node:timers/promises"; await loiter(500);
- hombre_fatal 2y agoSure, 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.