koa2

get请求的接收

const Koa = require('koa');
const app = new Koa();

app.use(async (ctx) => {
    let url = ctx.url;
    let req_query = ctx.query;
    let req_querystring = ctx.querystring;

    ctx.body = {
        url,
        req_query,
        req_querystring
    }
});

app.listen(3000, () => {
    console.log('[demo] server is starting at port 3000');
})

输出结果:

async/await

await必须放在async中

async:异步方法,await:接收异步方法返回的值(异步方法返回的值是:Promise异步对象)

async function testAsync(){
    return 'Hello async';
}
const result = testAsync();
console.log(result);

//Promise { 'Hello async' }
function takeLongTime() {
    return new Promise(resolve => {        //直接返回一个 Promise 异步对象
        setTimeout(() => {
            resolve('long_time_value');
        }, 1000);
    });
}

async function test() {
    const v = await takeLongTime();
    console.log(v);
}

test();

  

promise对象的使用

let state = 1;

function step1(resolve, reject) {
    console.log('1.洗菜');
    if(state == 1) {
        resolve('洗菜完成');
    } else {
        reject('洗菜错误');
    }
}

function step2(resolve, reject) {
    console.log('2.吃饭');
    if(state == 1) {
        resolve('吃饭完成');
    } else {
        reject('吃饭错误');
    }
}

function step3(resolve, reject) {
    console.log('3.洗碗');
    if(state == 1) {
        resolve('洗碗完成');
    } else {
        reject('洗碗错误');
    }
}

new Promise(step1).then(function(val) {    //new promise(step1).then().then().then()
    console.log(val);
    return new Promise(step2);
}).then(function(val) {
    console.log(val);
    return new Promise(step3);
}).then(function(val) {
    console.log(val);
})

  

const Koa = require('koa')
const app = new Koa()
 
app.use( async ( ctx ) => {    //ctx 相当于上下文对象(this是对上下文对象的引用)
  ctx.body = 'hello koa2'
})
 
app.listen(3000)
console.log('[demo] start-quick is starting at port 3000')

  

原文地址:https://www.cnblogs.com/qq254980080/p/9208702.html