Environment: node 8.11.x I want use async/await for sleep a while.
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms))
await sleep(5000)
This works.
const sleep = util.promisify(setTimeout)
await sleep(5000)
It cause a exception: TypeError: "callback" argument must be a function. setTimeout The document note: This method has a custom variant for promises that is available using util.promisify()
So what's the difference?
promisify
is expects a function that has final argument that is the callback.
In other a words it wants a function that looks like:
function takesACallback(str, Fn) {
Fn(null, "got: ", str)
// or with an error:
// Fn(error)
}
Of course setTimout
is the opposite. The argument you want to pass in is the last argument. So when you try to call the promisify
d function and pass in an argument, it will take that argument -- the delay-- and try to call it like a function. Of course that's an error.
For entertainment (and slight educational) purposes only, you can pass in a function that reverses the arguments and it will work:
let util = require('util')
let pause = util.promisify((a, f) => setTimeout(f, a))
pause(2000)
.then(() => console.log("done"))
Now the final argument of the function you passed to promisify
expects function. But the asyn/await
method is so much nicer…
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With