有条件的完成承诺

我有一个承诺链,我执行一些行动。 当我达成一个特定的陈述时,我想创build一个分支,它可能会继续链,否则,将解决整个即将到来的承诺链。

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