Nodejs api with Promisses

Asked

Viewed 104 times

2

I am developing an API in Typescript with Nodejs and Mariadb; when I do an operation with the bank, 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: I can use Promises on an API? Would you like it to look like this:

productDao.save({name:"Notebook Dell", price:"5000"})
.then(res => {
   //Caso tudo dê certo.
})
.catch(err => {
   //Caso algo dê errado.
})

But I wonder, The standard Promise is ideal for an API? What are the possible complications? What would be the disadvantages and advantages over this architecture in a API?

1 answer

2


You can use "old-fashioned" Promises or Callbacks as you like. The Promise approach has advantages:

  • errors launched within a Precedent call the catch and do not stop the script, unlike a normal function that stops execution when errors occur
  • a Promise allows chaining and to be included in high-order functions such as the Promise.all

Regarding API, it is a matter of preference.

  • 2

    Not to mention that using Promises the code is much more readable :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.