bluebird 流程控制?
昨天看了这个 bluebird 多层嵌套该如何优化。 地址 然后前天正好自己学习promise得时候先这么写了
checkMeetingPath = (meetingPath)->
console.log('s1')
return fs.existsAsync(meetingPath)
.then (exists)->
console.log('s2')
return fs.mkdirAsync(meetingPath)
.catch (exists)->
console.log('s8')
return fs.statAsync(meetingPath)
.then (stats)->
console.log('s5')
if stats.isDirectory()
console.log('s6')
return Promise.resolve()
else
console.log('s7')
return fs.unlinkAsync(meetingPath)
.then ()->
console.log('s3')
return fs.mkdirAsync(meetingPath)
昨天看了那个之后做了一点优化 如下:
checkMeetingPath = (meetingPath)->
notExists = (exists)->
console.log('s2')
return fs.mkdirAsync(meetingPath)
isExists = (exists)->
console.log('s8')
return fs.statAsync(meetingPath)
.then isDirectory
isDirectory = (stats)->
console.log('s5')
if stats.isDirectory()
console.log('s6')
return Promise.resolve()
# return Promise.reject('dd')
else
console.log('s7')
return fs.unlinkAsync(meetingPath)
.then notExists
console.log('s1')
return fs.existsAsync(meetingPath)
.then notExists
.catch isExists
感觉这样优化之后已经舒服了很多了。。不知道哪里可以更加舒服一点, 比如每个return得promise我加得这个then如何更加优雅什么得。
1 回复
var fs = require("fs");
var Promise = require('bluebird');
Promise.promisifyAll(fs);
var path = "aaa";
function notDirectory(path){
return(
fs.unlinkAsync(path)
.then(function(){
return fs.mkdirAsync(path)
})
)
}
function fileExist (path){
return(
fs.statAsync(path)
.then(function(stats){
return stats.isDirectory(path)
})
.then(function(isDirectory){
if (!isDirectory){
return notDirectory(path)
}
})
)
}
fs.existsAsync(path)
.then(function(){ //不存在
return fs.mkdirAsync(path);
},function(){ //存在
return fileExist(path)
})
.catch(function(err){
console.log(err)
})