这周看了nodejs的基本知识的视频,剩下的就是做任务了。现在先说一下学的东西有什么。
一、promise的三种状态
1.初始化,状态:pending(等待)
2.当调用resolve(成功),状态:pengding=>fulfilled(已完成)
3.当调用reject(失败),状态:pending=>rejected(已拒绝)
二、promise的then和catch方法
function delfile(){
return new Promise((reslove,reject)=>[
//异步操作
fs.unlink('./hehe.js',(err)=>{
if(err){
//失败
reject('失败了')//外部通过catch接收 表示失败的处理
}else{
reslove('成功了')//走then的处理函数 表示成功
}
})
])
}
delfile()
.then((msg)=>{
console.log('then:'+msg)
})
.catch((err)=>{
console.log('err:'+err)
})
promise必须实现then方法,而且Promise执行then后还是Promise,所以就可以根据这一特性,不断的链式调用回调函数,一组链式调用中只需要一个catch。
isExit()
.then(()=>{
console.log('is exit 的成功处理')
// return delFile()
})
.then(()=>{
console.log('删除文件的成功处理')
})
.then(()=>{
console.log('555555')
})
.catch((err)=>{
console.log('catch')
console.log(err)
})
终止链式调用就需要抛出一个错误,手动终止。
.then(()=>{
console.log('删除文件的成功处理')
throw new Error('手动终止')
})
本周总结完毕。下周继续努力。