Last active
August 21, 2020 20:43
-
-
Save jh3y/c7870ca6fb01d5e8577a9f1474a2c162 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
const PROB = 0.2 | |
const grabIngredient = ingredient => () => { | |
return new Promise((resolve, reject) => { | |
setTimeout(() => { | |
if (Math.random() > PROB) { | |
resolve(ingredient) | |
} else { | |
reject(`Sorry, we've got no ${ingredient}`) | |
} | |
}, Math.random() * 1000) | |
}) | |
} | |
// boilerplate functions for getting the different ingredients | |
const getButter = grabIngredient('Butter') | |
const getFlour = grabIngredient('Flour') | |
const getSugar = grabIngredient('Sugar') | |
const getEggs = grabIngredient('Eggs') | |
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 () => await Promise.all([ | |
getButter(), | |
getFlour(), | |
getSugar(), | |
getEggs(), | |
]) | |
// boilerplate async functions that return strings | |
const mix = async (ingredients) => `Mixing ${ingredients}` | |
const cook = async (cakeMix) => 'Hot Cake' | |
const stand = async (hotCake) => '🍰' | |
const bakeACake = async () => { | |
try { | |
const ingredients = await getIngredientsOnline() | |
const cakeMix = await mix(ingredients) | |
const hotCake = await cook(cakeMix) | |
const cake = await stand(hotCake) | |
console.info('BAKED', cake) | |
return cake | |
} catch (e) { console.info(e) } | |
} | |
bakeACake() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I think it needs to change from
to