3 ms·
> I'm trying to wrap my head around async/await and how it works under the hood, be it JavaScript, C# or others. Careful, it doesn't work the same way in every
by throw_m239339 5y ago
> I'm trying to wrap my head around async/await and how it works under the hood, be it JavaScript, C# or others.
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.
- gabes 5y agoThis 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.
- claytongulick 5y agoJS 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.
- ginko 5y ago> 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.
- endorphine 5y agoMy thoughts exactly.
- deleted 5y ago[deleted]
- claytongulick 5y agoI 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
- Blahah 5y agowhen 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.