Image for post
Image for post

The async and await keywords introduced in JavaScript make it easier to write asynchronous code that looks like synchronous code and is a bit less boilerplate-y. They are really just a small abstraction over promises though so if you don’t understand promises read this first.

An async function that returns a value

Functions prefixed with the async keyword implicitly return a promise. When the function returns a value the promise is fulfilled.

The async implementation of foo above is equivalent to the below implementation that explicitly returns a Promise

Using await keyword to block execution until a promise fulfills

Use the await keyword to stop a function from continuing until an async function completes.

Keep in mind that await can only be used inside an async function — hence why we use .then().catch() when calling bar() but inside bar() we can await the result of foo(). …


Image for post
Image for post

Think of a Promise like a container for a value that can only be known at some point in the future (like the result of a network call or reading a file from disk). They exist in one of three states:

  1. pending is the initial state before it has succeeded or failed.
  2. fulfilled when the promise has succeeded.
  3. rejected when the promise has failed.

A Promise has callback functions that are executed when its state changes to handle success or failure. These callbacks can themselves be a Promise allowing for Promise’s to be chained.

A function that returns a promise that fulfills

Calling resolve changes the promises state from pending to fulfilled causing the callback function in foo().then()

About

Iain Maitland

Senior software engineer at Skyscanner. I mostly write Java and Python back end systems occasionally foraying in to JavaScript. Also a dad and 49ers fan.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store