It is Obvious that in our application we need to wait for asynchronous tasks to complete. we generally handle these asynchronous tasks by using Promises or Observables.

The advantage of  asynchronous tasks is that we can execute multiple tasks in background and continue functioning.

But, If you misuse them then it will effect the performance of the application. For this purpose this quick read blog give you tips how and when to use Observables and Promises.

Now let us consider simple example with three functions with promises and for async we have used setTimeout().

function getFirstData() {

 return new Promise((resolve, reject) => {

 setTimeout(() => {
 resolve("First Data");
 }, 1000);

 });

}

function getSecondData() {

 return new Promise((resolve, reject) => {

 setTimeout(() => {
 resolve("Second Data");
 }, 1000);

 });

}

function getThirdData() {

 return new Promise((resolve, reject) => {

 setTimeout(() => {
 resolve("Third Data");
 }, 1000);

 });

}

 

 

Say for example if you want to execute all three functions at same time you would do something like below

getFirstData().then((data) => {
 /* do something */
});

getSecondData().then((data) => {
 /* do something */
});

getThirdData().then((data) => {
 /* do something */
});

If you want to do certain task after all the promises are resolved then you start calling in then().


getFirstData().then((data) => {
 console.log(“First Data Recieved”);

 getSecondData().then((data) => {
 console.log(“Second Data Recieved”);

 getThirdData().then((res) => {

 console.log(“Third data Recieved”);

 console.log(“All done do some task!”);

 });

 });

});

 

Actually there is no need to put them in then(). Now lets see how much time it will take to execute.


console.time("data");

getFirstData().then((data) => {


 console.log("First Data Received");

 getSecondData().then((data) => {


 console.log("Second Data Received");

 getThirdData().then((res) => {

 console.log("Third data Received");

 console.log("All done do some task!");

 console.time("data");

 });

 });

});

 

you will get output like

First Data Recieved
Second Data Recieved
Third data Recieved
All done do some task!
data: 3009.0419921875ms

We use promise.all() for these type of scenarios to accelerate overall execution.

console.time("data");
let promiseFirst = getFirstData();
let promiseSecond = getSecondData();
let promiseThird = getThirdData();

Promise.all([promiseFirst, promiseSecond, promiseThird]).then((result) => {

 console.timeEnd("data");
 console.log("First: ", result[0]);
 console.log("Second: ", result[1]);
 console.log("Third: ", result[2]);

});

 

The output will be something like

First: First Data
Second: Second Data
Third: Third Data
data: 1007.43994140625ms

Now the same thing you can achieve using Observables as well

let observableFirst = Observable.fromPromise(getFirstData());
let observableSecond = Observable.fromPromise(getSecondData());
let observableThird = Observable.fromPromise(getThirdData());

Observable.forkJoin([observableFirst, observableSecond, observableThird]).subscribe(result => {
console.log(result);
});

 

Dependent Tasks:

If the task is dependent on the other and rely on other  task then Promise.all() or Observable.forkJoin() will not work in such scenarios.

Say for example based on logged in user you want to fetch all orders immediately.

login(username, password).subscribe((result) => {

 getOrders(result.userId).subscribe((orders) => {

 /* do Something */

 });

});

This above way is not the best design but there will be such situations where you have to make such API requests but always try to understand the situation and implement Promises and Observables to achieve high Performance by using such as Promise.all() or Observable.forkJoin().

Looking for AngularJS Development Company? Hire our dedicated developers!

 

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

This site uses Akismet to reduce spam. Learn how your comment data is processed.