34

Choose Promise or Observable when working with Angular?

 4 years ago
source link: https://www.tuicool.com/articles/ma2M7r
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
rMNf2qN.png!webjIzaMjy.png!web

As you all know, and many articles have talked about this issue, Promise and Observable are the techniques used to process data asynchronously in javascript in general and Angular in particular. But what are the differences between these two guys? Which guy should I use? … Such questions have a lot of people asking, and in this article, I would like to give some personal analysis to choose the most suitable one.

1. Compare

Ability to return multiple results

  • For Promise, after each data processing, it can only return a single value.
const   p   =   new   Promise ( ( resolve ,   reject )   = >   { 

     if   ( true )   { 

         resolve ( 'Ket qua' ) ; 

     }   else   { 

         reject ( 'Co loi' ) ; 

     } 

 } ) ; 

 

 p . then ( result   = >   { 

     console . log ( result ) ; 

 } ) . catch ( error   = >   { 

     console . log ( error ) ; 

 } ) ; 

 

 // => Ket qua

With Observable, it can return multiple values ​​simultaneously.

const   ob   =   rxjs . Observable . create ( ( observer )   = >   { 

     observer . next ( 'Ket qua 1' ) ; 

     observer . next ( 'Ket qua 2' ) ; 

     observer . next ( 'Ket qua 3' ) ; 

 } ) ; 

 

 ob . subscribe ( ( result )   = >   { 

     console . log ( result ) ; 

 } ) ; 

 

 // => Ket qua 1 

 // => Ket qua 2 

 // => Ket qua 3

Cancellation capability

  • For Promise, when we have created a request, there is no way to cancel that request.
  • Observable, it is possible to cancel the created request.

Read More…


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK