0.4.6.1: Async Await
Learning Objectives
Async-await can be cleaner syntax but is functionally the same as
.then
syntaxHow to use async-await syntax to manage promise control flow in lieu of
.then
Try-catch syntax provides us
.catch
functionality with async-await syntax
Introduction
.then
syntax:
Async-await syntax:
Async-await syntax allows us to write asynchronous JavaScript in a synchronous manner, like in the example above. This can result in cleaner code, but does not add new functionality. Rocket does not have a strong preference whether to use async-await or .then
syntax.
async
specifies a given function is asynchronous and returns a promise, and await
will wait for a given promise to resolve before proceeding to the next line. async
and await
keywords must be used together; it is not meaningful to use async
without await
, and it is invalid to use await
without async
.
Example: Async-await with pg
pg
Async-await syntax is generally preferred due to its increased readability compared with .then
syntax.
.then
syntax:
Async-await syntax:
Here are the official docs on how to use pg
with async-await syntax in Express.
Example: Catch errors with async-await
Try-catch syntax allows us to catch errors with async-await syntax in the same way we would catch errors with .then
and .catch
syntax.
.then
syntax:
Async-await syntax:
Similar to .catch
syntax, when there is an error in a try
block, e.g. a request to a nonexistent URL, the error will cause our program will crash unless we catch that error in a catch
block. Try-catch syntax is not directly related to promises, but is commonly used with async-await promise syntax.
Example: Async-await does not pause programs, only code in current function
The following code executes "Before" and "After" console.log
s before "Recipes".
Output
getRecipes
will return before its logic has completed because it is an async
function that contains an asynchronous client.query
. async
wraps getRecipes
in a promise that returns immediately but resolves only when getRecipes
logic is complete. Since there is no .then
or await
on the getRecipes()
function call, the "After" console.log
runs before getRecipes
has resolved.
Example: Async-await works with all promises, including the promise returned by Promise.all
Promise.all
We can use async-await with Promise.all
to retrieve unrelated data concurrently with syntax that reads sequentially.
.then
syntax:
Async-await syntax: