xgqfrms™, xgqfrms® : xgqfrms's offical website of cnblogs! xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!

Koa 洋葱模型 All In One

Koa 洋葱模型 All In One

洋葱模型原理: 最先执行最内层,待完成后; 然后依次执行更外面一层的; 最后执行最外层的;

let context = {
  data: []
};

async function middleware1(ctx, next) {
  console.log('action 001', `1 begin ✅`);
  ctx.data.push(1);
  await next();
  console.log('action 006', `1 end ✅✅✅✅✅✅`);
  ctx.data.push(6);
}

async function middleware2(ctx, next) {
  console.log('action 002', `2 begin ✅✅`);
  ctx.data.push(2);
  await next();
  console.log('action 005', `2 end ✅✅✅✅✅`);
  ctx.data.push(5);
}

async function middleware3(ctx, next) {
  console.log('action 003', `3 begin ✅✅✅`);
  ctx.data.push(3);
  await next();
  console.log('action 004', `3 end ✅✅✅✅`);
  ctx.data.push(4);
}

Promise.resolve(middleware1(context, async() => {
  return Promise.resolve(middleware2(context, async() => {
    return Promise.resolve(middleware3(context, async() => {
      return Promise.resolve();
    }));
  }));
}))
  .then(() => {
    console.log('end');
    console.log('context = ', context);
  });

// "action 001"
// "action 002"
// "action 003"
// "action 004"
// "action 005"
// "action 006"

// "end"
// "context = { data: [1, 2, 3, 4, 5, 6]}"

demos

koa server


const Koa = require("koa");
const app = new Koa();

const log = console.log;
// logger
app.use(async (ctx, next) => {
  await next();
  // middleware 1, 后执行
  const rt = ctx.response.get("X-Response-Time");
  log(`\nmiddleware 1, 后执行`, rt);
  log(`${ctx.method} ${ctx.url} - ${rt}`);
});

// x-response-time
app.use(async (ctx, next) => {
  const start = Date.now();
  await next();
  // middleware 2, 先执行
  const ms = Date.now() - start;
  log(`\nmiddleware 2, 先执行`, `${ms}ms`);
  ctx.set("X-Response-Time", `${ms}ms`);
});

// response
app.use(async (ctx, next) => {
  // log(`response ctx`, ctx);
  // await next();
  log(`\nmiddleware 0, 最后的 middleware 最先执行`);
  ctx.body = "Hello World! <br />powered by koa.js";
});

app.listen(3000);
// app.listen(8080);


https://codesandbox.io/s/koa-server-b88bh

(🐞 反爬虫测试!打击盗版⚠️)如果你看到这个信息, 说明这是一篇剽窃的文章,请访问 https://www.cnblogs.com/xgqfrms/ 查看原创文章!

refs

https://chenshenhai.github.io/koajs-design-note/note/chapter02/02.html

https://segmentfault.com/a/1190000013981513

https://juejin.im/post/5d28616151882539af1913d2

https://github.com/webfansplz/article/issues/10

https://www.jianshu.com/p/c76d9ffd7899

https://github.com/xixigiggling/my-ice-cream/issues/34

https://github.com/mynane/sil-koa/blob/master/lib/index.js



©xgqfrms 2012-2021

www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!

原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!


posted @ 2020-05-07 12:16  xgqfrms  阅读(419)  评论(9编辑  收藏  举报