in this example from MDN, their are tried to show what is async chain if we use old-style async callbacks with an analogy of steps to take to eat a pizza.
chooseToppings(function(toppings) {
placeOrder(toppings, function(order) {
collectOrder(order, function(pizza) {
eatPizza(pizza);
}, failureCallback);
}, failureCallback);
}, failureCallback);
why in each step previous functions parameter passed as argument to inner function? and why they don't provide any code inside each function? is this below code better ?
chooseToppings(function(toppings) {
//some work with toppings
placeOrder(function(order) {
//some work with order
collectOrder(function(pizza) {
eatPizza(pizza);
}, failureCallback);
}, failureCallback);
}, failureCallback);
CodePudding user response:
There are two main ideas here:
toppings
is not a parameter ofchooseToppings
, but rather its result value. It is not areturn
value but passed asynchronously to the callback thatchooseToppings
receives. SochooseToppings
producestoppings
,placeOrder(toppings)
produces anorder
andcollectOrder(order)
produces apizza
.- Each function depends on the previous function's result. You cannot place an order without knowing the toppings. These dependencies are made explicit by passing through the value instead of being contextual. If you didn't have these dependencies, you could just call all the functions at once, without waiting for asynchronous results.
Why they don't provide any code inside each function?
Because these are just example functions, their implementation doesn't matter. You can assume that placeOrder
does all the // work with toppings
, whatever that is - the guide is only concerned with how these asynchronous functions are called in sequence.