What is the difference between Promises and Observables in Angular?

yshnv
Marvenics
Published in
2 min readAug 2, 2019

Introduction

First of all, Promise and Observable are used for handling Asynchronous Data in applications. In this article, we are gonna learn about the difference between Promise and Observable.

What is Promise?

A Promise is Future Value of an Event. In Angular when we are using API, Sockets, Timers like Time Delaying functionalities in a function X, we need to send back assurance for caller function of function X.

In other words, it is a relation between Callee and Caller Function, In which caller function believes that caller must return some value as resolution or reject.

For example :

getData() {
return this.http.get(this.apiUrl)
.toPromise()
.then(res => {
resolve(res);
})
.catch(err => {
console.log(err);
reject(err);
});
}

In this program, the function getData() returns a Promise which will be a success or failure. According to its request status, it will resolve or reject data. While the caller function waits until the data arrives from this function.

What is Observable?

An Observable is like a Steam (in many languages) and allows to pass zero or more events where the callback is called for each event. More than multiple events handling it helps us in asynchronous programming.

A third-party library called Reactive Extensions (RxJS) is used by Angular to use Observable.

For Example:

getData (): Observable<any[]> {
return this.http.get(this.apiUrl)
.map((res:Response) => res.json())
.catch((error:any) => Observable.throw(error.json().error || 'Server error'));
}

--

--

yshnv
Marvenics

Angular | Ionic Framework | ExpressJS | UIUX