Koa 洋葱模型
阅读原文时间:2023年07月10日阅读:1

Koa 洋葱模型

let context = {
  data: []
};

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

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

async function middleware3(ctx, next) {
  console.log('action 003');
  ctx.data.push(3);
  await next();
  console.log('action 004');
  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]}"


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

demo

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

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



xgqfrms 2012-2020

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


手机扫一扫

移动阅读更方便

阿里云服务器
腾讯云服务器
七牛云服务器

你可能感兴趣的文章