一、Koa是什么

Koa是什么
const Koa = require('koa')
const app = new Koa()
app.use(async(ctx,next) => {
ctx.body = 'hello koa'
})
app.listen(3000)

代码疑问

中间件——获取网络请求之前与之后的内容
// 执行顺序135 642
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);
二、异步的类型
- callback
- Promise
- async + await
// 1. callback
function ajax(fn) {
setTimeout(() => {
console.log('你好')
}, 2000)
}
ajax(() => {
console.log('执行结束')
})
// 2. Promise
// 此时delay()函数返回一个承诺。承诺2s后把word传递
function delay(word) {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(word)
}, 2000)
})
}
delay('孙悟空').then(() => {
console.log(word)
return delay('猪八戒')
}).then(() => {
console.log(word)
}).catch(
console.log(word)
)
//async + await
async function start() {
const word1 = await delay('孙悟空')
console.log(word1)
const word1 = await delay('猪八戒')
console.log(word1)
}
start()
网友评论