Hacker News new | past | comments | ask | show | jobs | submit login

> 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.




> 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.


My thoughts exactly.


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


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.


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.


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.




Join us for AI Startup School this June 16-17 in San Francisco!

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: