Sometimes you want to await on an async function but you are not in an async function already. How do you do this? You can create a new async function to wrap your await call:
async function doWork() {
await new Promise(resolve => setTimeout(resolve, 1000));
return { greeting: "hoot hoot" };
}
function notAsync() {
(async () => {
const data = await doWork();
console.log(data.greeting);
})();
}
Note that the notAsync
will not block and wait for doWork
to complete. This is not possible to do without blocking the UI as Javascript is single threaded.