JavaScript: Async / Await

Brief overview of promises

As JavaScript is a synchronous language (it can only handle doing one thing a time), promises allow us to delegate some tasks to somewhere else. Then when it’s done (successfully or not) we can choose to do something with the result.

function purchaseWine() { 
getWine()
.then(drinkWine)
.catch(reasonForDrinkingWater);
}

Async / Await — what’s the deal?

So the purchaseWine function above works fine, but we can now use async/await to write the same thing. Async/Await allows you to write asynchronous code that looks like synchronous code.

async function purchaseWine () {
async function purchaseWine() { 
const wine = await getWine();
drinkWine(wine);
}
async function purchaseWine() {
try {
const wine = await getWine();
drinkWine(wine);
} catch (reason) {
reasonForDrinkingWater(reason);
}
}

Why should I use it?

Async / await is even more useful when your promises become a little more complex. Specifically when you‘re passing results from one promise into another.

function purchaseWineAndCheese() { 
getWine()
.then(getComplementaryCheese)
.then((cheese) => enjoyWineAndCheese(wine, cheese)) // no wine!
.catch(reasonForDrinkingWater);
}
function getComplementaryCheese(wine) {
const cheese = wine === 'merlot' ? 'gouda' : 'cheddar';
return Promise.resolve({ wine, cheese });
}
function purchaseWineAndCheese() {
getWine()
.then(getComplementaryCheese)
.then(({ wine, cheese }) => enjoyWineAndCheese(wine, cheese))
.catch(reasonForDrinkingWater);
}
function getComplementaryCheese(wine) {
const cheese = wine === 'merlot' ? 'gouda' : 'cheddar';
return Promise.resolve(cheese);
}
async function purchaseWineAndCheese() {
try {
const wine = await getWine();
const cheese = await getComplementaryCheese(wine);
enjoyWineAndCheese(wine, cheese);
} catch (reason) {
reasonForDrinkingWater(reason);
}

--

--

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
Tara Ojo

Tara Ojo

Software engineer @ Google. She speaks and writes about career progression and front-end development. @tara_ojo