Angular - Promises Vs Observables

Introduction

In this article, we are going to discuss the differences between Promises and Observable in angular programming. This article can be used by beginners, intermediates, and professionals.

We are going to cover,

  1. Sync and Async
  2. Promises vs Observables

Prerequisite 

  1. Basic knowledge of Angular
  2. Basic knowledge of Promises and Observables.

Promises and Observables

We should understand Sync and Async first before we start on promises or observables.

In simple words, 

Sync – Thread will wait for a response.

Async - The thread will request data in the background and the main thread will not wait for a response.

It means,

Sync code is blocking in nature hence Async programming comes in to picture. 

Async programming is non-blocking and executes in the background without blocking the main thread.

Now a question comes in the mind, how will we have handled Async operations in Angular?

The answer would be using Promises or Observables.

Async operations can be handled in Angular either using promises or observables.

Now another question comes raised, what is the difference between them and when should we use what?

Differences between Promises and Observables

  1. Promise provides the data once data will be ready. While Observables provides data in chunks. 
  2. Promise provide data whether someone is using it or not, but observables provide data only if someone request/subscribe to it.
  3. A promise is native to JavaScript. Observables are part of RxJs not JavaScript.
  4. A promise can emit only a single value while an observable can return multiple values.
  5. Promise can’t cancel once created. Observables can be canceled using unsubscribe.
  6. Promises don’t have operators. Observables provided operators like maps, filters, reduce, and retry, which are useful for complex scenarios.
  7. Promises are eager. Observables are Lazy.

I hope you enjoy this article and find it useful.