-
-
Save windix/f443b3da9839e37f1f1f551b524ff7e0 to your computer and use it in GitHub Desktop.
Baking a cake with async + await
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// helper function for stock check | |
const doTheyHaveIt = () => Math.random() > 0.1 | |
// boilerplate functions for getting the different ingredients | |
const getButter = () => new Promise((resolve, reject) => { | |
setTimeout(doTheyHaveIt() ? resolve('Butter') : reject('Sorry, no butter'), 1000) | |
}) | |
const getFlour = () => new Promise((resolve, reject) => { | |
setTimeout(doTheyHaveIt() ? resolve('Flour') : reject('Sorry, no flour'), 1000) | |
}) | |
const getSugar = () => new Promise((resolve, reject) => { | |
setTimeout(doTheyHaveIt() ? resolve('Sugar') : reject('Sorry, no sugar'), 1000) | |
}) | |
const getEggs = () => new Promise((resolve, reject) => { | |
setTimeout(doTheyHaveIt() ? resolve('Eggs') : reject('Sorry, no eggs'), 1000) | |
}) | |
const getIngredientsFromTheSuperMarket = async () => { | |
try { | |
const butter = await getButter() | |
const flour = await getFlour() | |
const sugar = await getSugar() | |
const eggs = await getEggs() | |
return [ | |
butter, | |
flour, | |
sugar, | |
eggs, | |
] | |
} catch (e) { return e } | |
} | |
const getIngredientsOnline = async () => { | |
try { | |
return await Promise.all([ | |
getButter(), | |
getFlour(), | |
getSugar(), | |
getEggs(), | |
]) | |
} catch (e) { return e } | |
} | |
// boilerplate async functions that return strings | |
//const mix = async (ingredients) => 'Cake Mix' | |
const mix = async (ingredients) => { | |
if (Array.isArray(ingredients)) { | |
console.log('Cake Mix: ', ingredients) | |
return true | |
} else { | |
console.log('Missing ingredients: ' + ingredients) | |
throw ":(" | |
} | |
} | |
const cook = async (cakeMix) => 'Hot Cake' | |
const stand = async (hotCake) => '🍰' | |
const bakeACake = async () => { | |
try { | |
//const ingredients = await getIngredientsFromTheSuperMarket() | |
const ingredients = await getIngredientsOnline() | |
const cakeMix = await mix(ingredients) | |
const hotCake = await cook(cakeMix) | |
const cake = await stand(hotCake) | |
return cake | |
} catch (e) { | |
return e | |
} | |
} | |
// create a fresh cake and log it in the callback | |
const freshCake = bakeACake() | |
.then((cake) => console.info(cake)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment