Choose Promise or Observable when working with Angular?

Tram Ho

As you 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.

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

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.

Retry ability

  • Promise cannot retry when the error handling process occurs, or it must be thanks to 3rd party support tips and libraries.
  • The Observable provides retry operators, retryWhen makes it easy to retry requests.

Build web application with Python + Flask Framework + Angular2 + DynamoDB – Part 1
Why Angular made me want to quit programming

Ability to process results before returning

  • With Promise, because the feature only returns a single result, the processing of the results can be done in the step after receiving the results .

  • With Observable, it provides a lot of powerful operators for processing results before returning.

Refer to more operators here: https://www.learnrxjs.io/operators

2. Conclusion

So you can see the Observable has proved its strength better than Promise so my choice is to use Observable in Angular. It’s also no coincidence that Angular chose the Observable to develop it right! Hopefully, through this sketchy article, you also have your own evaluation of these two guys and have the right choice when working with Angular.

Don’t blame the Framework: Experience when working with Angular and React
Build web application with Python + Flask Framework + Angular2 + DynamoDB – Part 2
Share the news now

Source : viblo