Reputation: 31
I am working On NodeJS
Project , I used Promise In my code
to chain some methods , I needed to abort in one of the 'thens' chain
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);
})
Upvotes: 1
Views: 425
Reputation: 19296
If I understand the intention correctly, there is no need here to cancel or throw.
You should be able to achieve your ends by rearrangement :
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);
});
That should work with the proviso that a log
object is always delivered to SaveEmployeeLogToDb
via all possible paths to that point, as implied by the original code.
Upvotes: 2
Reputation: 1673
You can't currently "cancel" promises. But you can use an exception for that purpose:
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);
}
//****
})
Upvotes: 0