创建了一个空文件夹后,如果你要使用npm,必须执行
npm init (一路回车即可)
在安装了koa2以后,我们需要
const Koa = require('koa')
const app = new Koa()
app.use(async(ctx)=>{ //ctx封装了request,response
ctx.body = 'hello'
})
app.listen(3000)
中间件(洋葱圈模型)
const Koa = require('koa');
const app = new Koa()
app.use(async(ctx,next)=>{ //async干嘛的呢?这里还看不出,当next变成异步的就有趣了,下一大段给你解释
ctx.body = '1'
//下一个中间件
next() //假如注释了,则不会进入下一个中间件,因此只有12
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'
})
//结果135642
//当next是异步执行时
app.use(async(ctx,next)=>{
ctx.body = '1'
//异步进入下一个中间件,这时候输出只有1和2,因为next()是异步的,当12执行完后执行next,这时候网络请求都已经结束了
setTimeOut(()=>{
next()
},2000)
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'
})
//古老的异步解决方案(陷入回调地狱)
function ajax(fn){
setTimeOut(()=>{
console.log('你好');
fn()
},1000)
}
ajax(()=>{
console.log('执行一结束')
ajax(()=>{
console.log('请求二执行结束')
ajax(()=>{
console.log('请求三执行结束')
})
})
})
//是时候解决了,第二代解决方案,promise,es6原生支持
function delay(word){
return new Promise((reslove,reject)=>{
setTimeOut(()=>{
reslove(word)
},2000)
})
}
delay('孙悟空')
.then((word)=>{
console.log(word) //孙悟空,promise时用then接收到了resolve的参数
return delay('猪八戒')
})
.then((word)=>{
console.log(word) //猪八戒
return delay('沙悟净')
})
.then((word)=>{
console.log(word) //沙悟净
})
//.catch作错误处理
//整个都是平级的,不用陷入回调地狱,但是代码还是有点麻烦
//终极解决方案async+await
async function start(){ //await一定要在函数内部使用,等待一个异步函数的执行完成,这样就没有了异步的痕迹,变成了同步的
const word1 = await delay('孙悟空') //沿用上面的delay函数,等待delay执行完毕
console.log(word1)
const word2 = await delay('猪八戒') //沿用上面的delay函数
console.log(word1)
const word3 = await delay('沙悟净') //沿用上面的delay函数
console.log(word1)
//这样就按顺序下来了
}
mysql的一些初步使用
//mac下面安装mysql
brew install mysql
mysql.server start //启动服务
//登入mysql
mysql -u (你的用户名) -p (你的密码)
show databases //查看现在有哪些数据库,假如我们现在有cAuth数据库
//进入cAuth数据库
use cAuth;
show tables; //看看里面cAuth有什么表格,假如有test,我们看看test里面有什么
desc test;
//如果想看更加乱的数据
select * from test
//如果只想看test里面具体到openID的一项
select openID from test
//如果我们想删除test
drop table test;