十一、promise异步
对于node大部分都是异步函数,在处理异步函数的时候,为了顺序执行,需要在回调里嵌套回调,就会导致回调地狱,为了解决这个问题,可以使用promise来处理,async/await处理。
- 删除文件使用promise简单实现:
function delLink(){
const fs=require('fs');
return new Promise((res, rej)=>{
fs.unlink('./index.js', (err)=>{
if(err){
rej('-文件不存在-');
}else{
res('-删除成功-');
}
})
})
}
delLink().then(res=>{
console.log(res);
}).catch(rej=>{
console.log(rej)
});
那么promise实现解决回调地狱的方式,就是通过链式调用。
- 链式调用判断文件是否存在,存在就删除文件:
function isPresence(){
const fs=require('fs');
return new Promise((res,rej)=>{
fs.stat('./index.js', (err, stats)=>{
if(err){
rej('文件不存在');
}else{
res('文件存在');
}
})
})
}
function delLink(){
const fs=require('fs');
return new Promise((res, rej)=>{
fs.unlink('./index.js', (err)=>{
if(err){
rej('-文件删除失败-');
}else{
res('-文件删除成功-');
}
})
})
}
isPresence().then(res=>{
console.log(res);
return delLink()
}).then(res=>{
console.log(res);
}).catch(rej=>{
console.log(rej);
})
注意: 链式调用只有一个catch来捕获错误。那么如何手动终止一个promise函数的执行呢?遇到错误就会停止,throw new Error(‘抛出错误’);来终止promise的执行。在使用链式调用的时候注意,要在最后一个then的前一个then返回一个promise对象。
十二、node连接mongodb数据库使用mongoose插件
1、操作数据库的步骤:
(1)、连接数据库
(2)、 创建一个和集合相关的schema对象,类似表头
(3)、 获取schema对象
(4)、 将schema对象转化成数据模型
(5)、 操作数据库(增,删,改,查)
- 连接数据库
const mongoose=require('mongoose');
mongoose.connect('mongodb://localhost/blog', {useNewUrlParser: true});
// 连接数据库
let db=mongoose.connection;
db.on('error',console.error.bind(console, '连接失败'));
db.once('open',function(){
console.log('连接成功');
})
// 创建一个和集合相关的schema对象,类似表头
const Schema = mongoose.Schema;
// 获取schema对象
const userSchema=new Schema({
name: {type: String, required: true},
pass: {type: String, require: true},
age: Number,
sex: {type:Number, default:0},
})
// 将schema对象转成数据模型
const User = mongoose.model('user', userSchema); //该数据对象和集合关联 ('集合名',schema对象)
User.insertMany({name: '刘', pass: 'hand123', age: 32}).then(res=>{
console.log("插入成功");
}).catch((rej)=>{
console.log(rej, '插入失败');
}); // 使用模型像users表里插入数据
// 注意:如果建的表为单数,系统会自动变为复数,在单词后加s
mongoose操作数据库通过创建scheme对象。需要修改几个表的数据,就要创建几个schema对象。
2、实现数据库增删改查操作,详情查看mongoose中文网api内容
// 查询操作
User.find({name: '刘'}).then(res=>{
console.log("查询成功", res);
}).catch((rej)=>{
console.log(rej, '查询失败');
});
// 删除操作
User.remove({name: '刘'}).then(res=>{
console.log("删除成功" ,res);
}).catch((rej)=>{
console.log(rej, '删除失败');
});
// 更新数据
User.updateMany({name: '刘'}, {name: '张'}).then(res=>{
console.log("修改成功" ,res);
}).catch((rej)=>{
console.log(rej, '修改失败');
});
3、为了防止频繁的启动服务,有一个nodemon工具,会监听代码变更自动的启动服务,安装时候要全局安装
npm install nodemon -g
再次启动服务时候使用,nodemon serve.js即可