I'm using bluebird in node with express ,when I return res.end(),Promise still goes to the next chain,here's my code:
Promise.resolve(operate).then(function(data){
if (!!data && data.length !=0) {
log.info('success');
return true;
}else {
log.warn('fail');
return res.end();
}
}).then(function(data){
if(data) {
log.info('done');
return res.end();
}else {
log.warn('fail');
return res.end();
}
})
And I got 2 'fail' in the log if it's failed,how can i make it stop if i got 'fail' in the first time?Thank you!
bluebird version:~2.10.2; node: 4.3.1; express:~4.2.0
You can return either an error or a rejected promise instead of res.end
. This will skip all success handlers until the end of the promise chain (technically until the first rejection handler):
Promise.resolve()
.then(() => Promise.reject())
.then(
() => console.log('this does not run'), // <-- success handler
() => console.log('this runs') // <-- rejection handler
);
So in your code:
Promise.resolve(operate).then(function(data){
if (!!data && data.length !=0) {
log.info('success');
return true;
} else {
log.warn('fail');
res.end();
return Promise.reject(/* optionally pass an error */); // <--- return rejected promise
}
}).then(function(data){
// this won't run if previous promise rejects
})