我怎么能放弃JavaScript的承诺?

我在NodeJS项目上工作,我用Promise在我的代码中链接了一些方法,我需要在“thens”链中的一个中止

 findEmployeeByCW('11111', "18-09-2016"). then(function () { return findEmployeeByCWE('111111', "18-09-2016", '111111') }, function () { console.log('createEmployeeLoginBy') createEmployeeLoginBy('111111', "18-09-2016", '111111'). then(function (log) { SaveEmployeeLogToDb(log) // *************** // ^_^ I need to exit here .... }) }) .then(function (log) { return updateLoginTimeTo(log, '08-8668', '230993334') }, function () { return createNewEmployeeLog('224314', "18-09-2016", '230993334', '08-99') }) .then(SaveEmployeeLogToDb).then(DisplayLog).catch(function (e) { console.log(e); }) 

如果我正确理解了这个意图,这里就没有必要取消或抛出。

你应该能够通过重新安排达到目的:

 findEmployeeByCW('11111', "18-09-2016") .then(function() { return findEmployeeByCWE('111111', "18-09-2016", '111111') .then(function(log) { return updateLoginTimeTo(log, '08-8668', '230993334'); }, function(e) { return createNewEmployeeLog('224314', "18-09-2016", '230993334', '08-99'); }); }, function(e) { return createEmployeeLoginBy('111111', "18-09-2016", '111111'); }) .then(SaveEmployeeLogToDb) .then(DisplayLog) .catch(function(e) { console.log(e); }); 

这应该与前提条件是,通过所有可能的path,始终将log对象传递给SaveEmployeeLogToDb ,如原始代码所暗示的。

您目前不能“取消”承诺。 但是你可以使用一个例外来达到这个目的:

 findEmployeeByCW('11111', "18-09-2016"). then(function () { return findEmployeeByCWE('111111', "18-09-2016", '111111') }, function () { console.log('createEmployeeLoginBy') //*** "return" added return createEmployeeLoginBy('111111', "18-09-2016", '111111'). then(function (log) { SaveEmployeeLogToDb(log) //**** throw new Error('promise_exit'); //**** }) }) .then(function (log) { return updateLoginTimeTo(log, '08-8668', '230993334') }, function () { return createNewEmployeeLog('224314', "18-09-2016", '230993334', '08-99') }) .then(SaveEmployeeLogToDb).then(DisplayLog).catch(function (e) { //**** //Only log if it's not an intended exit if(e.message != 'promise_exit'){ console.log(e); } //**** })