I have this request handler, it looks like this:
router.post('/', function(req,res) {
var screencast;
var channel;
youtube.get(req.body.videoId).then(function(data) {
screencast = data.screencast;
channel = data.channel;
}).then(function() {
return connection.beginTransactionAsync();
}).then(function() {
return connection.queryAsync('INSERT IGNORE INTO Channels SET ?', channel);
}).then(function() {
return connection.queryAsync('INSERT INTO Screencasts SET ?', screencast)
}).then(function() {
return connection.commit();
}).error(function(e) {
connection.rollback();
});
});
Sometimes I want to break the promise chain early and send an error. Here is what I tried:
router.post('/', function(req,res) {
var screencast;
var channel;
youtube.get(req.body.videoId).then(function(data) {
if (data === null) {
res.send('error: video does not exist.');
return;
}
screencast = data.screencast;
channel = data.channel;
}).then(function() {
console.log('trace: starting transaction');
return connection.beginTransactionAsync();
}).then(function() {
return connection.queryAsync('INSERT IGNORE INTO Channels SET ?', channel);
}).then(function() {
return connection.queryAsync('INSERT INTO Screencasts SET ?', screencast)
}).then(function() {
return connection.commit();
}).error(function(e) {
connection.rollback();
});
});
While the error is shown, the promise chain demonstrably does not break; the next function is called.
My question is, how do I break the promise chain early to send an error?
Something that I tried was to introduce one more level of indentation:
youtube.get(req.body.videoId).then(function(data) {
if (data === null) {
res.send('error: video does not exist.');
return;
}
connection.beginTransactionAsync().then(function() {
return connection.queryAsync('INSERT IGNORE INTO Channels SET ?', channel);
}).then(...
I found this to work however, I am apprehensive to use more nesting, as I also need to check whether the video has already been stored in the database before processing, requiring two levels of indentation, maybe more.
I found two other answeres (one) however, they have not been helpful to me. My question relates specifically to Bluebird and Express.