For a simple async sleep function in JavaScript, await promisify(setTimeout)(ms)
works!
But how? The arguments look wrong.
setTimeout(ms, errorCallback)
which should not work, yet it does. How?
import { promisify } from 'util'
(async () => {
// const start = Date.now()
await promisify(setTimeout)(1000)
// console.log(Date.now() - start)
})()
node <<HEREDOC
(async () => {
// const start = Date.now();
await require('util').promisify(setTimeout)(1000);
// console.log(Date.now() - start);
})()
HEREDOC
Background: await setTimeout(() => {}, 1000)
doesn't work. This one-liner: await new Promise(resolve => setTimeout(resolve, 1000))
did not work for me (why?). We can promisify it manually: const sleep = ms => new Promise(resolve => setTimeout(resolve, ms)); await sleep(1000)
, but that is an extra function. We can do better.
This is because setTimeout
has a custom promisified function now. You can find it when you print setTimeout
.
> console.log(setTimeout)
{ [Function: setTimeout] [Symbol(util.promisify.custom)]: [Function] }
undefined
Common functions that take a callback not in the standard way may have a custom promisified function, and util.promisify
returns it when a function has a custom promisified function.