Re:Node.js 16 Available Now
by eloff on Tuesday April 20, 2021 @02:35PM
(#26879021)
You can also do this with a wrapper around setTimeout, if you're in an older environment:
[ Parent
| on HN ]
... or even more easily by:
const wait = require('util').promisify(setTimeout)
That's interesting. util.promisify normally only works with functions where the callback is the final argument, which isn't the case with setTimeout. I didn't know you could customize promisify behaviour, but looking at the docs apparently you can just by setting a property on the object using the util.promisify.custom symbol [1]. That is what setTimeout is doing, which is why that code works.
[1] https://nodejs.org/dist/latest-v16.x/docs/api/util.html#util...
Re:Node.js 16 Available Now
by motogpjimbo on Wednesday April 21, 2021 @03:34AM
(#26886463)
You don't need `async` here, since your function explicitly returns a promise.
I do that too. In ts, it helps a tiny bit - it enforces that the function will return a promise. So if that ever changes, the function TS compiler will be your backup anchor.
While this is true, I've found over time it's easier for me to quickly see in my code if I need to `await` on something if the function is an `async` function and not just that it returns a Promise.
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.
The problem is that this is more than just a syntactic difference. There's a chance it will take two ticks to resolve instead of one.
For documentation purposes, I recommend block-commenting the `async`:
const foo = /async/ () => new Promise(...);
I did not know this and appreciate the insight! Will definitely store this back of mind and try and remember to use block comments when needing to explicitly return a promise.
That's not true if you just return the promise instead of using return await, right?
No. `async` on a function automatically defers it even if the return value is immediate.
> async function foo() { return "hello"; } foo().then(console.log); console.log("after")
after hello
const sleep = ms => new Promise(r => setTimeout(r, ms));
It doesn't need to be that tricky.
I get that the arrow function notation is less verbose, but I disagree with calling function syntax "tricky". It really doesn't matter much. You need the type on ms though (if using typescript), and export.