NodeJs api with promisses

2

I'm developing an API in TypeScript with NodeJS and MariaDB; when I do an operation with the bank, right below I have a if to check if an error has 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.
})

However, 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 an API ?

    
asked by anonymous 29.06.2017 / 19:46

1 answer

2

You can use Promises or Callbacks "old fashioned" as you prefer. The promises approach has advantages:

  • errors posted within a promise call catch and do not stop the script, as opposed to a normal function that stops execution when there are errors
  • a promise allows chaining and be included in high order functions like Promise.all

Regarding the API, it's a matter of preference.

    
29.06.2017 / 20:14