有条件地完成链中的承诺

Conditionally finish promise in chain

我有一个 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.'));

这可能与承诺有关吗?

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

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.'));

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

  .finally(() => console.log('Done!'))
  .catch(() => console.log('Error.'));