
Promise is a mechanism in which we can perform asynchronous tasks.
OK first I’ll briefly explain what an asynchronous task is.
Asynchronous versus Synchronous
In the synchronous operations, when performing one operation, the program waits until that operation is finished and then goes to the next.
But, one of the major drawbacks of this synchronous operation is the wastage of time. If the first operation is consuming some time or waiting until some requirement is fulfilled, it’s better to move ahead for the next operation. This is asynchronous processing.
This may arise a problem. What if we need some value returned from the first operation? Then, it should give a PROMISE 😉 to return that value, maybe, after some time, so that the other operations can keep the promise and perform their jobs.
In cases where the first operation fails to give the value as expected, the error handling should be done accordingly.
As noted, a promise represents a value that may be available in future, or never. It is even possible that the may be available at the time the promise is created. Which means, we can make promises even to the operations that can be done synchronously, not needed though 🙂

As shown in the figure above, in a synchronous task queue, the tasks are performed one after the other. The second is done after the completion of the first task and so on.
But in the asynchronous operation on the right, the task2 gives out a promise, and the program simply jumps to the task3 without further waiting for the final outputs of the second task.
An example
Suppose in your angular application, you want to fetch some data from a server. Of course, there will be a certain latency or a delay in the server response.
Perhaps, the server might down and may never return any data. That means, our application is never going to start in synchronous mode until the server returns a response.
Therefore, we can use promises to make the http request an async one.
Structure of a promise
We can create a promise as a function.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
promise_func(){ return new Promise(resolve, reject)=>{ //perform some async operation and get the result if(success){ resolve(result); } else{ reject(error); } } } |
This can be thought of as a service function. Here, it’s clear that when anyone calls the function, a Promise object is returned.
The actual results of the asynchronous operation are extracted from the Promise as follows.
1 2 3 4 5 6 7 8 9 10 11 |
promise_func() .then(result =>{ //use the result of the async operation }) .catch(error=>{ //error handling }); |
First, we call the promise_func(). A promise is returned immediately after calling the function. Then we chain the operation to get the result when the promise delivers it.
Example
Let’s get back to the server example. I have created a small demo app using angular and JSON server. The angular app sends a HTTP get request to the JSON server with promises and display some posts of a website. Here’s how the app would look like.

To simulate the server side, you may consider JSON-server. To install JSON server run
1 |
npm install -g json-server |
The JSON server needs a JSON file to run the server. For that, check the db.json file in the git repo.
Then open a terminal window in the folder having the db.json file and run,
1 |
json-server –delay 3000 –watch db.json |
The json-server can be accessed from the url http://localhost:3000
Here, we add a delay of 3000 ms (3 seconds) to simulate the delay of an actual server response.
To run the front-end angular application, first run
1 |
npm install |
to install the dependencies and then
1 |
ng serve |
to launch the app.
Code
Here’s the code for the ‘service function’ part. Here’s the link to the git repo of the complete demo.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
import { Injectable } from '@angular/core'; import { URL } from '../../assets/urls'; import { HttpClient } from "@angular/common/http"; @Injectable() export class PostsService { url:string = URL; constructor(private http: HttpClient) { } public getPosts(){ let promise = new Promise((resolve, reject) => { this.http.get(this.url) .toPromise() .then( res => { resolve(res); }, msg => { reject(msg); } ); }); return promise; } } |
The code is available in a file called posts.service.ts. I have added it as a service. Any component get the service simply by importing it. The getPost() method will return a promise object and the actual data from the server response is read in the postsComponent as follows.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
import { Component, OnInit } from '@angular/core'; import { PostsService } from '../../services/posts.service'; @Component({ selector: 'app-posts', templateUrl: './posts.component.html', styleUrls: ['./posts.component.css'] }) export class PostsComponent implements OnInit { private posts; constructor(private postsService: PostsService) { } ngOnInit() { this.postsService.getPosts().then(posts => { this.posts = posts; }); } } |
The data from the promise are assigned to the this.posts variable. Then, to display the data, the html template file can refer this.posts variable. But notice that it would take more than 3 seconds to get this data from the server and the html template would be rendered before reaching the server response. Therefore, at the time of html file referring the posts variable in the ts file, it would be undefined since no value is assigned yet. Therefore, note that *ngIf is used in
1 2 |
<div style="color: #1a1a1a; background-color: #eee; min-height: 300px; padding: 24px;" *ngIf="posts"> |
is to avoid generation of errors due to undefined variable. It will only render when posts variable is assigned a value after about 3 seconds.