Lesson 15

Speeding up Observables & Promises

Executing promises and observables efficiently

PRO

Lesson Outline

Speeding up Observables & Promises

Often in our applications we need to wait on some kind of asynchronous task to complete, and we generally handle the responses from these asynchronous tasks using either Promises or Observables. The great thing about asynchronous tasks is that it allows our application to continue functioning whilst the tasks are completed in the background, and we can even run multiple asynchronous tasks at the same time.

However, it is easy to negatively impact the performance of your application by misusing promises or observables. For the purpose of this lesson, I have created a demo application that contains a service with three methods:

getThingOne(){
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve("thing one");
    }, 2000);
  });
}

getThingTwo(){
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve("thing two");
    }, 2000);
  });
}

getThingThree(){
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve("thing three");
    }, 2000);
  });
}

The purpose of this is to simulate an asynchronous task that takes some time to complete (like a call to a server), in this case each task takes two seconds to complete.

Executing Multiple Promises or Observables

If we wanted to execute multiple promises at the same time we might just do something like this:

ngOnInit(){

	this.dataService.getThingOne().then((res) => {
		/* do something */
	});

	this.dataService.getThingTwo().then((res) => {
		/* do something */
	});

	this.dataService.getThingThree().then((res) => {
		/* do something */
	});

}

No problems here, all of these tasks will execute in parallel and finish at roughly the same time. Meaning after two seconds we will have all of the results we need.

However, it is common for an application to need to wait for some data before continuing with a certain task. To make sure that that task is not executed before the data has been returned from the promise, we generally make a call to that function inside of the .then() handler, or we could use the async/await syntax.

PRO

Thanks for checking out the preview of this lesson!

You do not have the appropriate membership to view the full lesson. If you would like full access to this module you can view membership options (or log in if you are already have an appropriate membership).