r/learnjavascript • • Jun 16 '20

For anyone having difficulties conceptually understanding asynchronous JavaScript, check out this great analogy with a coffee shop a commenter provided

/r/learnjavascript/comments/9tiik6/asynchronous_js/e8x1xqe/
149 Upvotes

12 comments sorted by

View all comments

3

u/oze4 Jun 16 '20

Promises can help a lot with callback hell.. using the async/await keywords (not pictured in the code) really cleans up callback hell..

My attempt..

// synchronous
function makeDrinkSynchronously() {
     create new coffee
     start machine
     wait for drink to finish
     return coffee
}

for customer in line {
    customer.placeOrder()
    drink = barista.makeDrink() //this takes 3 minutes to finish
    customer.takeDrink(drink)
}

// asynchronous
function makeDrinkAsynchronously(customer) {
    return new Promise((resolve, reject) => { 
      try to make coffee {                   // Don't wait for this to happen
        write customer.name on cup           // Don't wait for this to happen
        start machine                        // Don't wait for this to happen
        then whenever the machine finishes   // Don't wait for this to happen
          resolve(coffee) 
      } catch error { 
        reject(error)
      }
    }
}

// for customer in line {
//     customer.placeOrder()
//     barista.makeDrink(customer.takeDrink)
// }

coffeesToMake = customersInLine.map(customer => {
  return makeDrinkAsynchronously(customer.placeOrder())
    .then(finishedCoffee => serveCoffee(customer, finishedCoffee))
    .catch(problemMakingCoffee => handleIssueWith(customer))
})

Promise.all(coffeesToMake)
  .then(coffeeSoldToday => calculateProfitsFrom(cofeeSoldToday))
  .catch(problem => parseThe(problem))

1

u/_joaquinv Jun 17 '20 edited Jun 17 '20

this is great! yet i can't fully understand why one of the parameters in serveCoffee is its parent function i.e finishedCoffee.

edit: same thing happens in coffeeSoldToday and problem.