let app = {};
app.middlewares = [];
app.use = function (fn) {
  this.middlewares.push(fn);
}
// reduce  
app.use(async (next) => {
  console.log(1);
  // Next equals incoming () => dispatch(index+1)
  await next();// write next in KOA must write await
  console.log(3);
})
app.use((next) = > {
  console.log(2)
  //next()
  console.log(4);
});
// app.use((next) => {
// console.log(5)
// next()
// console.log(6);
// });
function dispatch(index){
  if (index === app.middlewares.length) return;
  let middle = app.middlewares[index]; // The first one is called by default
  // Pass the method in the second array
  // () => dispatch(index+1)
  middle((a)= > dispatch(index+1)); / / () = > {} = > next function

  /** * App.middlewares [0] = app.use(async (next) => {} So * (next) => {first middle console.log(1); 2 next(); console.log(3); 4} Execute middle(() => dispatch(index+1)). Next () => dispatch(index+1) prints console.log(1) and next() executes The dispatch function fetches the second middleware (next) => {second middle console.log(2); console.log(4); } * print 2,4 execute print 3 */
}
dispatch(0);
//1 2 5 6 4 3
Copy the code