Koa

一、Koa是什么

Koa_第1张图片
Koa是什么
const Koa = require('koa')
const app = new Koa()


app.use(async(ctx,next) => {
    ctx.body = 'hello koa'
})

app.listen(3000)
Koa_第2张图片
代码疑问

Koa_第3张图片
中间件——获取网络请求之前与之后的内容
// 执行顺序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);

二、异步的类型

    1. callback
    1. Promise
    1. 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()

你可能感兴趣的:(Koa)