Skip to content

Instantly share code, notes, and snippets.

@jh3y
Last active August 21, 2020 20:43
Show Gist options
  • Save jh3y/c7870ca6fb01d5e8577a9f1474a2c162 to your computer and use it in GitHub Desktop.
Save jh3y/c7870ca6fb01d5e8577a9f1474a2c162 to your computer and use it in GitHub Desktop.
Baking a cake with async + await
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()
@mgcation
Copy link

mgcation commented Sep 5, 2018

I think it needs to change from

...
setTimeout(doTheyHaveIt() ? resolve... : reject... , 1000)
...

to

...
setTimeout(() => doTheyHaveIt() ? resolve... : reject... , 1000)
...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment