by throw_m239339 · 4y ago · 0 comments
Careful, it doesn't work the same way in every single language that has these keywords.
> Why can't non-async functions use await()?
Because in Javascript at least, it only makes sense to await a promise, nothing more. A function marked as async will always return a promise. You can't await on anything that is not a promise.
I understand that async functions return promises, but why can't you await for a promise from a non-async function? For me it would seem logical since by awaiting you essentially turn a promise into a concrete result which you can then use in your non-async code.
It's perfectly valid to await on a literal:
> async function test() {
let a = "yep";
await a;
console.log(a);
}
> test()
> yep> async function test() {
let a = "yep";
return await a;
}> let b = test()
> console.log(b)
> Promise { 'yep', [Symbol(async_id_symbol)]: 1215, [Symbol(trigger_async_id_symbol)]: 5, [Symbol(destroyed)]: { destroyed: false } }
The promise you create with `await a` resolves immediately (equivalent to Promise.resolve(a)), but it's still a promise.
I use this all the time in async functions with code branches, some of which await and some return an immediate value.