Monday, May 20, 2024
106
rated 0 times [  111] [ 5]  / answers: 1 / hits: 156093  / 8 Years ago, sun, may 8, 2016, 12:00:00

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' );
}

More From » asynchronous

 Answers
8

async/await is not magic. An async function is a function that can unwrap Promises for you, so you'll need api.on() to return a Promise for that to work. Something like this:



function apiOn(event) {
return new Promise(resolve => {
api.on(event, response => resolve(response));
});
}


Then



async function test() {
return await apiOn( 'someEvent' ); // await is actually optional here
// you'd return a Promise either way.
}





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:



async function whatever() {
// snip
const response = await test();
// use response here
// snip
}

[#62262] Thursday, May 5, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
brodyfrancisi

Total Points: 1
Total Questions: 102
Total Answers: 89

Location: Marshall Islands
Member since Mon, May 31, 2021
3 Years ago
;