My notes and reminders for handling promises with
await In Real Life.
As I see it, the idea is to switch to using
await when working with promise-returning, asynchronous operations (such as
fetch) because it lends itself to more flexible and readable code.
async keyword, when used before a function declaration like so
async function f()):
- defines an asynchronous function i.e. a function whose processes run after the main call stack and doesn’t block the main thread.
- always returns a promise. (Its return value is implicitly wrapped in a resolved promise.)
- allows us to use
- use the
asyncfunctions to wait for a Promise.
- Example usage:
const users = await fetch('/users')).
- It makes the
asyncfunction pause until that promise settles and returns its result.
- It makes sense that it may only be used inside
asyncfunctions so as to scope the “waiting” behaviour to that dedicated context.
- It’s a more elegant syntax for getting a promise‘s result than
- If the promise resolves successfully,
awaitreturns the result.
- If the promise rejects,
awaitthrows the error, just as if there were a
throwstatement at that line.
throwcauses execution of the current function to stop (so the next statements won't be executed), with control passed to the first
catchblock in the call stack. If no
catchblock exists among caller functions, the program will terminate.
- Given this “continue or throw” behaviour, wrapping an
try...catchis a really nice and well-suited pattern for including error handling, providing flexibility and aiding readability.
try...catch -based example. (NB let’s assume that we have a list of blog articles and a “Load more articles” button which triggers the
Here’s another example. Let’s say that we needed to wait for multiple promises to resolve:
await within a
try...catch is my favourite approach but sometimes it’s not an option because we’re at the topmost level of the code therefore not in an
async function. In these cases it’s good to remember that we can call an
async function and work with its returned value like any promise, i.e. using