JavaScript: Async / Await

Brief overview of promises

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

Async / Await — what’s the deal?

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?

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);
}

--

--

--

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

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Easy way to use Supermemo18 on wine

Testing with Jest: 15 Awesome Tips and Tricks

JPA big pit, unable to automatically generate creation time in the current_at field like mybaits

What happened in the simulation

Frame VS Bounds

How to make XSS payload manually

The No Bullsh*t guide to GraphQL in .Net Core Part 3

⏰ Optimize Angular Component Test Performance

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

More from Medium

Intro To JavaScript Unit Testing

How to Use JavaScript Arrays Like a Pro

Javascript Scope & Closure

JavaScript Objects