一、安装与搭建
安装
1.脚手架安装koa2
npm install -g koa-generator
2.建立项目
koa2 项目名称
3.启动
npm start server
搭建
express中自带路由, koa2中需要自己安装: npm install koa-router
// 注意koa2是基于async/await操作中间件,目前node.js 7.x的harmony模式下才能使用,
const koa = require('koa')
const app = new koa()
//express 自带路由
//koa需要自己配置 就是中间件
//express 写法
// app.use((req, res) => {
// res.send('返回数据');
// })
//中间件
app.use(async (ctx) => {
ctx.body = 'hello world';
})
app.listen(3000);
二、异步函数(async/await)
async函数返回的是promise对象,并且把内部的值进行promise 封装, 如果promise对象通过 then或者catch 方法又注册了回调函数, async 函数执行完成之后 注册的回调函数就会放到异步的队列中, 等待执行
async function timeout(){
return 'hellow'
}
console.log(timeout())
显示在前台相面返回的是promise对象,要获得 async 函数的执行结果时, 需要调用 promise 的 then 或者 catch 来给它注册回调函数
async function timeout_01() {
return 'hello koa'
}
timeout_01().then(result => {
console.log(result)
})
如果 async 函数执行完, 返回的promise 没有注册 回调函数, 比如函数内部做了一次for循环, 你会发现函数的调用 就是执行了函数体, 和普通函数没有区别,唯一的区别在于 函数 执行完成之后 返回一个 promise对象
async function timeout_01() {
for (let index = 0; index < 3; index++) {
console.log('async'