For a simple async sleep function in JavaScript, await promisify(setTimeout)(ms) works!
But how? The arguments look wrong.
- promisify passes an error callback, so the
- setTimeout call would be 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.
 
    