如何链接多个 Promise?

jon*_*ona 5 javascript fs node.js promise bluebird

我不太确定,也许我错过了一些明显的东西,但我不知道如何链接两个承诺。

我的基于回调的代码看起来像这样:

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)
    })
  })
}
])
Run Code Online (Sandbox Code Playgroud)

我已经开始尝试将其重构为基于承诺的流程,这就是我到目前为止所拥有的:

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)
})
}
Run Code Online (Sandbox Code Playgroud)

(我使用的是Bluebird,所以我Promise.promisifyAll(fs)之前也这样做过)

问题是,我不知道将上一个系列的第二个“步骤”放在哪里。我是否将其放入then或放入其功能中?我是否要返回它并将其放入单独的函数中?

任何帮助将不胜感激。

tad*_*man 4

通常承诺驱动的代码如下所示:

operation.then(function(result) {
  return nextOperation();
}).then(function(nextResult) {
  return finalOperation();
}).then(function(finalResult) {
})
Run Code Online (Sandbox Code Playgroud)

您的示例中发生了很多事情,但总体思路如下:

Promise.resolve().then(function() {
  if (nodir) {
    return fs.mkdir('somedirectory').catch(function(err) {
      log('error while trying to create the directory:\n\t %s', err);
      process.exit(0);
    });
  }
}).then(function() {
  return fs.readFile(path.dirname(__dirname) + '/util/sample_config.yml').catch(function(err) {
    log('error while reading the sample file:\n\t %s', err);
    process.exit(0);
  })
}).then(function(sampleContent) {
  log('pulled sample content...');

  return fs.writeFile('db/config.yml', sampleContent).catch(function(err) {
    log('error writing config file:\n\t %s', err)
    process.exit(0)
  })
}).then(function() {
  log('successfully wrote file to %s/db/config.yml', process.cwd())
})
Run Code Online (Sandbox Code Playgroud)

这假设您使用的所有调用都是 Promise 本机的。

最初的Promise.resolve()只是以承诺开始链条,因为你的第一步是有条件的。