NodeJs api with promises
I am developing an API in TypeScript with NodeJS and MariaDB; when I do an operation with the bank, just below I have a if to check if any error occurred.
productDao.save({name:"Notebook Dell", price:"5000"}, function(err, res){
if(err){
//Código para caso algo dê errado.
}else{
//Código se tudo der certo.
}
})
The case is: Can I use promises in an API? I would like it to look something like this:
productDao.save({name:"Notebook Dell", price:"5000"})
.then(res => {
//Caso tudo dê certo.
})
.catch(err => {
//Caso algo dê errado.
})
But, I wonder, is the default promise ideal for an API? What are the possible complications? What would be the disadvantages and advantages over this architecture in a API ?
2
Author: Márcio Eric, 2017-06-29
1 answers
You can use Promises or "old-fashioned" Callbacks as you like. The promises approach has advantages:
- errors thrown within a promise call
catch
and do not stop the script, unlike a normal function that stops execution when there are errors - promise allows chaining and being included in high-order functions such as
Promise.all
Regarding API, it is a matter of preference.
2
Author: Sergio, 2017-06-29 18:14:56