Home > Mobile >  why in the this example from mdn each inner function takes previous (parent) function parameters as
why in the this example from mdn each inner function takes previous (parent) function parameters as

Time:10-25

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 of chooseToppings, but rather its result value. It is not a return value but passed asynchronously to the callback that chooseToppings receives. So chooseToppings produces toppings, placeOrder(toppings) produces an order and collectOrder(order) produces a pizza.
  • 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.

  • Related