Promises and async/await: a simple example

Pepe is a cook from Barcelona. He wants to prepare the best tortilla de patatas in the city, but he doesn't have the ingredients:

  1. 🥔 Potatoes
  2. 🥚 Eggs
  3. 🧂 Salt
  4. 🧴 Olive oil

Pepe asks his coworkers if they could buy the ingredients; each of them agrees to buy one ingredient:

  1. Paco → 🥔
  2. Manu → 🥚
  3. Luis → 🧂
  4. Juan → 🧴

Getting ingredients

Each coworker works at his own pace, but they all are reliable and they promise they will bring the ingredients.

For example, Paco promises he can get back with potatoes after 1 min (60000 ms).

jsx

const getPotatoes = () => {

    const promise = new Promise( (resolve, reject) => {
        
        setTimeout( () =>  resolve('🥔 Potatoes') , 60000);
    
    });
    
    return promise;

}

Manu will come back with eggs in 2 min (120000 ms):

jsx

const getEggs = () => {

    const promise = new Promise( (resolve, reject) => {
        
        setTimeout( () =>  resolve('🥚 Eggs') , 120000);
    
    });
    
    return promise;

}

Luis will do it in 4 min (240000 ms):

jsx

const getSalt = () => {

    const promise = new Promise( (resolve, reject) => {
        
        setTimeout( () =>  resolve('🧂 Salt') , 240000);
    
    });
    
    return promise;

}

And Juan willl do it in 8 min (480000 ms):

jsx

const getOliveOil = () => {

    const promise = new Promise( (resolve, reject) => {
        
        setTimeout( () =>  resolve('🧴 Olive oil') , 480000);
    
    });
    
    return promise;

}

Await 1 Vespa

Coworkers need to share Pepe's motorbike (a 1984 Vespa 🛵). That means: Paco will go first for potatoes, then Manu will go for eggs, then Luis will go for salt and, lastly, Juan will bring back olive oil.

Meanwhile, Pepe waits for the ingredients while drinking wine:

jsx
const getIngredients = async () => {

    // Pepe begins to drink wine here 🍷

    await getPotatoes(); // 1 minutes
    await getEggs(); // 2 minutes
    await getSalt(); // 4 minutes
    await getOliveOil(); // 8 minutes
    
    // After 1 + 2 + 4 + 8 = 15 min he has the ingredients
    // Pepe stops to drink wine here 🥴
    // He can begin to cook the tortilla 
    

}

Await 4 Vespas

Pepe realizes that 15 mins to have all the ingredients is a lot of time. What would happen if he needed to cook a receipt with more ingredients (like paella)?

For the sake of his business, Pepe buys 4 motorbikes (one Vespa for each coworker). Now, if he wants to cook a tortilla de patatas, he can get the ingredients faster:

jsx
const getIngredients = async () => {

    // Pepe begins to drink wine here 🍷

    await Promise.all([getPotatoes(), getEggs(), getSalt(), getOliveOil()]);
    
    // After 8 minutes he will have all the ingredients
    // Pepe stops to drink wine here 🥴
    // He can begin to cook the tortilla
    

}

Hi, I'm Erik, an engineer from Barcelona. If you like the post or have any comments, say hi.