我不太确定,也许我错过了一些明显的东西,但我不知道如何链接两个承诺。
我的基于回调的代码看起来像这样:
async.series([
function (cb) {
// Create the directory if the nodir switch isn't on
if (!nodir) {
fs.mkdir('somedirectory', function (err) {
if (err) {
log('error while trying to create the directory:\n\t %s', err)
process.exit(0)
}
log('successfully created directory at %s/somedirectory', process.cwd())
cb(null)
})
}
cb(null)
},
function (cb) {
// Get the contents of the sample YML
fs.readFile(path.dirname(__dirname) + '/util/sample_config.yml', function (err, c) {
var sampleContent = c
if (err) {
log('error while reading the sample file:\n\t %s', err)
process.exit(0)
}
log('pulled sample content...')
// Write the config file
fs.writeFile('db/config.yml', sampleContent, function (err) {
if (err) {
log('error writing config file:\n\t %s', err)
process.exit(0)
}
log('successfully wrote file to %s/db/config.yml', process.cwd())
cb(null)
})
})
}
])
我已经开始尝试将其重构为基于承诺的流程,这就是我到目前为止所拥有的:
if (!nodir) {
fs.mkdirAsync('somedirectory').then(function () {
log('successfully created directory at %s/somedirectory', process.cwd())
}).then(function () {
// how can I put fs.readFileAsync here? where does it fit?
}).catch(function (err) {
log('error while trying to create the directory:\n\t %s', err)
process.exit(0)
})
}
(我使用的是蓝鸟,所以我这样做了Promise.promisifyAll(fs)
before)
问题是,我不知道将上一个系列的第二个“步骤”放在哪里。我把它放进去吗then
或者在它的功能中?我是否要返回它并将其放入单独的函数中?
任何帮助将不胜感激。