Re:Ask HN: Why can't await be used from non-async functions?
by ginko on Monday February 28, 2022 @01:06PM
(#30502914)
> A function marked as async will always return 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.
Re:Ask HN: Why can't await be used from non-async functions?
by endorphine on Monday February 28, 2022 @03:26PM
(#30504677)
My thoughts exactly.
Re:Ask HN: Why can't await be used from non-async functions?
by claytongulick on Monday February 28, 2022 @01:11PM
(#30502988)
I think this is technically incorrect.
It's perfectly valid to await on a literal:
> async function test() {
let a = "yep";
await a;
console.log(a);
}
> test()
> yep
Re:Ask HN: Why can't await be used from non-async functions?
by Blahah on Monday February 28, 2022 @01:24PM
(#30503143)
when you use `await a`, a is wrapped in a promise. Try returning await a - you get a promise and not the literal. In your example you don't use the promise, and a is a literal.
> 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.
Re:Ask HN: Why can't await be used from non-async functions?
by gabes on Monday February 28, 2022 @01:03PM
(#30502885)
This isn't _exactly_ true. JS will await on anything that is Promiselike (an object with a `then` function that accepts a callback). See the TS definition of Promiselike.
Re:Ask HN: Why can't await be used from non-async functions?
by claytongulick on Monday February 28, 2022 @01:17PM
(#30503051)
JS will await on literals too, it just immediately resolves to the value of the literal.
I use this all the time in async functions with code branches, some of which await and some return an immediate value.
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.