Call async from non-async
inspired by https://javascript.info/task/async-from-regular and the StackOverflow discussion https://stackoverflow.com/questions/59121611/how-to-call-async-function-from-web-of-non-async-functions
by Andy Bulka
HTML
<p>
Open the jsfiddle console to view the log messages.
</p>
JavaScript
// Problem: we want to call this async function 'wait' from a non async function
async function wait() {
await new Promise(resolve => setTimeout(resolve, 1000));
return 10;
}
// Solution 1. Use a promise rather than await, however this means you have to
// move any code that runs after the async call into a callback handler
function solution1() {
console.log('starting solution1')
wait().then(result => {
const r = result
console.log('done', r)
});
}
// Solution 2. If you don't need to wait for the result, dispatch an event and
// listen for the event using an async listener,
// which can indeed live inside a non async function
function solution2() {
console.log('starting solution2')
document.addEventListener("runwait", async function(event) {
const r = await wait()
console.log('done', r)
});
document.dispatchEvent(new CustomEvent('runwait', {
detail: {} // use a detailObject to pass parameters, if needed
}));
}
// Solution 3. Give in and make this calling function async if you can.
// However this means that any functions that call this function
// themselves have to be async, and so on.
async function solution3() {
console.log('starting solution3')
const r = await wait()
console.log('done', r)
}
solution1()
solution2()
solution3()