JavaScript Async/Await
With the official addition of promises in 2015, asynchronous
programming in JavaScript finally reached a stage where everyone
easily could write and make use of JavaScript's asynchronous
features. But the Promise syntax is verbose and a long chain of
promises can be hard to read. In 2017 the async and await keywords
were introduced to function as a syntactic sugar on top of promises
making code using promises easier to read and write.
The async keyword is used to tag a function as a function returning
a Promise. The return value of functions tagged with async is
automatically converted to promises.
The await keyword waits for a Promise to settle. This keyword is
only permitted inside async functions and blocks execution of the
code that follows until the specified Promise has settled.
Code example: just syntactic sugar
const fn = () => {return new Promise((resolve, reject) => {resolve(123)})}
is equivalent to
const fn = async () => {return 123}
Notice the reduction in verbosity when using async instead of the
explicit Promise.
Since async functions just make it easier to write functions that
return promises, we can of course use the normal Promise then and
catch methods.
Code example: await
The code below uses made up functions just to show the concept.
const getPicture = async userName => {const id = await userApi.getId(userName)const imageServer = await serverApi.getServer(id)const picture = await imageApi.getPicture(imageServer, id)return picture}
which is essentially the same as writing the code below using promises.
const getPicture = userName => {return new Promise((resolve, reject) => {useApi.getId(userName).then(id => serverApi.getServer(id)).then(imageServer => imageApi.getPicture(imageServer, id))})}
The function using the async and await syntax is significantly
easier to read and almost seems like a simple synchronous function.
Read more on MDN
Making asynchronous programming easier with async and await