安裝
npm i koa -S
開(kāi)始
const Koa = require('koa')
const app = new Koa()
app.use(async(ctx) => {
ctx.body = 'hello koa'
})
app.listen(3000)
什么是ctx
ctx就是封裝了request和response的上下文
什么是next
下一個(gè)中間件
什么是app
啟動(dòng)應(yīng)用
中間件
中間件是一種洋蔥圈的模型,當(dāng)你從中間件1next到了中間件2,最終你還將回到中間件1
image.png
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,next的作用就是執(zhí)行下一個(gè)中間件
async await
解決callback hell
一個(gè)Promise的例子
const ajax = (word) => {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(word)
}, 1000);
})
}
ajax('you')
.then(res => {
console.log(res)
return ajax('me')
})
.then(res => {
console.log(res)
})
async + await的例子
async + await一定要一起使用
async function start() {
const word1 = await ajax('you')
console.log(word1)
const word2 = await ajax('me')
console.log(word2)
const word3 = await ajax('him')
console.log(word3)
}
start()