koa await next()

當(dāng)一個(gè)中間件調(diào)用 next() 則該函數(shù)暫停并將控制傳遞給定義的下一個(gè)中間件。當(dāng)在下游沒(méi)有更多的中間件執(zhí)行后,堆棧將展開(kāi)并且每個(gè)中間件恢復(fù)執(zhí)行其上游行為。

// require("babel-register");
const http = require('http');
const https = require('https');
const Koa = require('koa');
const nexttest = require("./nexttest");
const app = new Koa();


// x-response-time
app.use(async (ctx, next) => {
  const start = Date.now();
  console.log('------1---------');
  await next();
  console.log('------2---------');

  const ms = Date.now() - start;
  ctx.set('X-Response-Time', `${ms}ms`);
});

// logger
app.use(async (ctx, next) => {
  const start = Date.now();
  console.log('------3--------');

  await next();
  console.log('------4---------');

  const ms = Date.now() - start;
  console.log(`${ctx.method} ${ctx.url} - ${ms}`);
});

app.use(async (ctx, next) => {
  console.log('------5--------');

  await next();
  console.log('------6---------');

});

// response
app.use(async ctx => {
  console.log('------7---------');

  ctx.body = ctx.response.status;
});

http.createServer(app.callback()).listen(3000);
// https.createServer(app.callback()).listen(3000);

輸出:

------1---------
------3--------
------5--------
------7---------
------6---------
------4---------
GET / - 2
------2---------
------1---------
------3--------
------5--------
------7---------
------6---------
------4---------
GET / - 0
------2---------
------1---------
------3--------
------5--------
------7---------
------6---------
------4---------
GET /favicon.ico - 0
------2---------
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Spring Cloud為開(kāi)發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見(jiàn)模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,506評(píng)論 19 139
  • github地址,歡迎大家提交更新。 express() express()用來(lái)創(chuàng)建一個(gè)Express的程序。ex...
    Programmer客棧閱讀 2,808評(píng)論 0 1
  • Koa 學(xué)習(xí) 歷史 Express Express是第一代最流行的web框架,它對(duì)Node.js的http進(jìn)行了封...
    Junting閱讀 2,927評(píng)論 0 0
  • Koa 必須使用 7.6 以上的版本。如果你的版本低于這個(gè)要求,就要先升級(jí) Node。 基本用法 Koa 提供一個(gè)...
    Gukson666閱讀 2,548評(píng)論 0 1
  • 楔子 七月的江南,悶得人透不過(guò)氣,合歡坐在空調(diào)房里,翹著二郎腿跟學(xué)姐侃大山。顧成譯的電話就是在這個(gè)時(shí)候打來(lái)的。 看...
    柚子小七_(dá)9abe閱讀 301評(píng)論 0 0

友情鏈接更多精彩內(nèi)容