When using a simple callback such as in the example below:
test() {
api.on( 'someEvent', function( response ) {
return response;
});
}
How can the function be changed to use async / await? Specifically, assuming 'someEvent' is guaranteed to be called once and only once, I'd like the function test to be an async function which does not return until the callback is executed such as:
async test() {
return await api.on( 'someEvent' );
}
It's annoying that there isn't a straightforward solution, and wrapping
return new Promise(...)
is fugly, but I have found an ok work-around usingutil.promisify
(actually it also kinda does the same wrapping, just looks nicer).The above function does not return anything, yet. We can make it return a
Promise
of theresponse
passed incallback
by doing:Now we can actually
await
thecallback
.Some rules when using
util.promisify
callback
must be the last argument of the function that is gonna bepromisify
(err, res) => {...}
Funny thing is we do not need to ever specifically write what's the
callback
actually is.You can achieve this without callbacks , use promise async await instead of callbacks here how I would do this. And also here I have illustrated two methods to handle errors
async/await
is not magic. An async function is a function that can unwrap Promises for you, so you'll needapi.on()
to return a Promise for that to work. Something like this:Then
But that's a lie too, because async functions also return Promises themselves, so you aren't going to actually get the value out of
test()
, but rather, a Promise for a value, which you can use like so: