koa是什么?
koa基于Nodejs平臺(tái)的下一代web開(kāi)發(fā)框架(上一代是express)。
- Express原班人馬打造,更精簡(jiǎn)。
- Async+await處理異步
- 洋蔥圈型的中間件機(jī)制。
用法很簡(jiǎn)單:
mkdir koa-demo
npm init
npm install koa --save
文件夾中新建一個(gè)server.js
const Koa = require('koa')
const app = new Koa()
app.use(async(ctx, next) => {ctx.body = 'hello'})
app.listen(3000)//端口3000
node server.js
就可以訪問(wèn)localhost:3000了。
ctx是什么呢?封裝了request和response的上下文。
next是什么呢?下一個(gè)中間件。
app是什么呢?啟動(dòng)應(yīng)用
中間件機(jī)制:
const Koa = require('koa')
const app = new Koa()
app.use(async(ctx, next) => {
ctx.body = '1'
next()
ctx.body += '2'
})
app.use(async(ctx, next) => {
ctx.body += '3'
next()
ctx.body += '4'
})
app.use(async(ctx, next) => {
ctx.body += '5'
next()
ctx.body += '6'
})
app.listen(3000)
結(jié)果是:135642
下面這個(gè)圖可以解釋這個(gè)機(jī)制。
洋蔥圈
寫一個(gè)小插件
新建一個(gè)koa-logger.js
module.exports = async(cxt, next) => {
const start = new Date().getTime();
await next();
const end = new Date().getTime();
console.log(cxt.request.url, end-start, cxt.body.length)
}
在server.js里引用
const koalog = require('./koa-logger.js')
app.use(koalog)
就可以在命令行中顯示出地址,耗時(shí)。
koa-router也很簡(jiǎn)單
安裝
npm install koa-router --save
引入
const Router = require('koa-router')
const router = new Router()
使用
router.get('/', (ctx, next) => {
//根目錄
})
router.get('/1', (ctx, next) => {
//
})
.
.
.
app.use(router.routes())
.use(router.allowedMethods())
async和await優(yōu)雅的處理異步
function ajax() {
setTimeout(() => {
console.log('你好')
}, 1000)
}
ajax()
console.log('sean')
我們都知道輸出sean 1秒之后再輸出你好。
異步編程的幾個(gè)方法:
- callback回調(diào)函數(shù),很古老的東西了。
function ajax(fn) {
setTimeout(() => {
console.log('你好')
fn()//回調(diào)函數(shù)
}, 1000)
}
var fn = function () {
console.log('sean')
}
ajax(fn)
回調(diào)函數(shù)的優(yōu)點(diǎn)是簡(jiǎn)單、容易理解和部署,缺點(diǎn)是不利于代碼的閱讀和維護(hù),各個(gè)部分之間高度耦合(Coupling),流程會(huì)很混亂,而且每個(gè)任務(wù)只能指定一個(gè)回調(diào)函數(shù)。如果回調(diào)函數(shù)中再嵌套回調(diào)函數(shù)的話,就行成了回調(diào)地獄(callback hell)
- promise
function delay(word) {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(word)
}, 1000)
})
}
delay('鳴人').then((word) => {
console.log(word)
return delay('佐助')
}).then((word) => {
console.log(word)
return delay('小櫻')
}).then((word) => {
console.log(word)
})
//鳴人,佐助,小櫻
promise鏈?zhǔn)秸{(diào)用:會(huì)將前一個(gè)then的返回值(return)作為下一次成功的回調(diào)函數(shù)的參數(shù)。
- async+await (必須一起使用)
function delay(word) {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(word)
}, 1000)
})
}
async function start() {
const word1 = await delay('鳴人')
console.log(word1)
const word2 = await delay('佐助')
console.log(word2)
const word3 = await delay('小櫻')
console.log(word3)
}
start()
簡(jiǎn)單明了。