有条件地完成链条承诺

cor*_*vid 1 javascript node.js promise ecmascript-6 bluebird

我有一个Promise链,我执行了许多操作.当我达到某个then陈述时,我想创建一个可以继续链的分叉,否则,将解决整个即将到来的承诺链.

readFile('example.json').then(function (file) {
    const entries = EJSON.parse(file);
    return Promise.each(entries, function (entry) {
      return Entries.insertSync(entry);
    });
  }).then(function () {
    if (process.env.NODE_ENV === 'development') {
      return readFile('fakeUsers.json');
    } else {
      // I am done now. Finish this chain.
    }
  })
  // conditionally skip these.
  .then(() => /** ... */)
  .then(() => /** ... */)
  // finally and catch should still be able to fire
  .finally(console.log.bind('Done!'))
  .catch(console.log.bind('Error.'));
Run Code Online (Sandbox Code Playgroud)

这可能与承诺有关吗?

the*_*eye 5

您可以将条件then处理程序附加到条件本身中返回的promise,就像这样

readFile('example.json').then(function (file) {
    return Promise.each(EJSON.parse(file), function (entry) {
      return Entries.insertSync(entry);
    });
  }).then(function () {
    if (process.env.NODE_ENV === 'development') {
      return readFile('fakeUsers.json')
        .then(() => /** ... */ )
        .then(() => /** ... */ );
    }
  })
  .finally(console.log.bind('Done!'))
  .catch(console.log.bind('Error.'));
Run Code Online (Sandbox Code Playgroud)

如果您使用的是Node.js v4.0.0 +,那么您可以使用这样的箭头函数

  .finally(() => console.log('Done!'))
  .catch(() => console.log('Error.'));
Run Code Online (Sandbox Code Playgroud)