Reputation: 4476
Currently I developing web app for nodejs using popular sequelize orm and typesciprt. Here is a example from my code
this.createNewGame(player.idPlayer).then((game) => {
this.getBestScore(player.idPlayer).then((bestScore) => {
defer.resolve({
idGame: game.idGame,
bestScore: bestScore
});
}).catch((error) => { defer.reject(error); });
}).catch((error) => { defer.reject(error); });
Here is one of the method
private getBestScore(idPlayer: number): Q.Promise<number> {
var defer = this.q.defer<number>();
GameModel.max<number>('score', { where: { 'idPlayer': idPlayer } }).then((result) => {
defer.resolve(result);
}).catch((error) => { defer.reject(error); });
return defer.promise;
}
I use catch in every method implementation and also in every call to method. I would like to have only one catch block in my expressjs router. I tried code like this and it works just fine, here is example:
//code in GameService class ...
getData(): Q.Promise<number> {
var defer = this.q.defer<number>();
this.method1().then((result) => {
defer.resolve(result);
});
return defer.promise;
}
private method1(): Q.Promise<number> {
var defer = this.q.defer<number>();
throw 'some error occurs here';
return defer.promise;
}
//router call GameService
router.get('/error-test', (req: express.Request, res: express.Response) => {
gameService.getData().then((result) => {
res.json(result);
}).catch((error) => { res.send(error); });
//works fine, here I get my thrown error
});
But in my previous example I need to use catch blocks everywhere otherwise If I get Unhandled rejection SequelizeDatabaseError or any other Unhandled rejection, nodejs stops working. Why I can't use only one catch block in my expressjs router when using calls to db with sequalize, like in my first example?
Upvotes: 0
Views: 480
Reputation: 28798
Sequelize operations return promises, so there is no reason to put Q into the mix. This is equivalent
private getBestScore(idPlayer: number): Q.Promise<number> {
return GameModel.max<number>('score', { where: { 'idPlayer': idPlayer } });
}
It doesn't return a Q.Promise
(sequelize uses bluebird), but the implementations should be interoperable, since they are both 'thenables'.
Upvotes: 2