0

I've been using the async/await keywords a lot lately with JavaScript Promise objects and I love it, but I don't understand what the purpose of the async keyword really is.

Why is it necessary to use the async keyword for functions that use await?

damd
  • 6,116
  • 7
  • 48
  • 77

1 Answers1

3

Functions marked async always return a promise (as opposed to regular functions):

When an async function is called, it returns a Promise. When the async function returns a value, the Promise will be resolved with the returned value. When the async function throws an exception or some value, the Promise will be rejected with the thrown value.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function#Description

robertklep
  • 198,204
  • 35
  • 394
  • 381
  • 1
    Just to clarify, async is a syntactic sugar. It saves you some typing needed to handle promises and stuff. But most importantly, **async allows you to use await keyword within the function**. You cannot await anything from a non-async function. – netchkin May 12 '17 at 09:16
  • 1
    @netchkin _"async is a syntactic sugar"_ and _"async allows you to use await keyword within the function."_ contradict each other. – a better oliver May 16 '17 at 11:28
  • @zeroflagL: good point! I have indeed misused the term "syntactic sugar". What I meant was it saves you some typing if you'd write promise-based code manually. – netchkin May 16 '17 at 11:48