十一、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即可