r/learnjavascript • u/gotta-lot • 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/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.
2
1
-2
Jun 16 '20
I think it's pretty well spelled out here. https://stackoverflow.com/questions/2035645/when-is-javascript-synchronous#:~:text=JavaScript%20is%20only%20asynchronous%20in,be%20running%20at%20this%20point.
Asynchronous just means one after the other. Which shouldn't be confused with parallel processes which on demand (service worker) is really js binding to the browser. Not ecma! So js is not a parallel.
For nodejs again it just binds to a c libuv and again nothing to do with ecma. So still js is not parallel.
So when people throw around concurrency or parallel or asynchronous... It is really miss leading a lot of people when it comes to js. Stop it!
The only way it could be ever is through c++ but it's not.
-5
14
u/gotta-lot Jun 16 '20
Shoutout to u/ucladurkel