TypeScript async callback with parameters

JavaScript is a single-threaded application and if we continue using that thread for all tasks, user will end up waiting for other tasks which will hamper user experience. To solve this problem, we have asynchronous programming.

TypeScript supports callback functions to make your program asynchronous. A callback function is a function which is scheduled to be called after some asynchronous processing is completed. The callback functions are passed to another function as parameters which allows them to be called when the async processing is completed.

Callback in Angular2/TypeScript

Mostly, you will have callback function calls after a long running process such as fetching data from online REST APIs. Let’s see an example of this usage.

export class Employee {
  constructor(public id: number) {
  }
}

In service class, you can create method which can accept parameter of function type. After method is done processing the request, it will execute the callback function with data that needs to be passed.

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Employee } from '../model/employee';
import { Observable } from 'rxjs';
 
@Injectable({
  providedIn: 'root'
})
export class EmployeeService {

  constructor(private http: HttpClient) { }

  public getEmployees(callBackUpdateUIElements: function): Observable<Employee[]> 
  {
    const url = 'http://localhost:3000/employees';

    this.http.get<Employee[]>(url)().subscribe(response => 
    {
      this.employees = response.map( item => 
      {
        return new Employee( 
            item.id
        );
      });

      callBackUpdateUIElements(this.employees);
    });
  }
}

In component file, create callback function which needs to be executed after a service call is successfully completed.

import { Component } from '@angular/core';
import { EmployeeService } from './service/employee.service';
import { Employee } from './model/employee';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent {
	title = 'app';
	employees = new Array<Employee>();

	private callBackUpdateUIElements(employees: Employee[]) {
  		this.employees = employees;

  		//More Logic and code here
  	}

	constructor( empService:EmployeeService ) {
		empService.getEmployees(callBackUpdateUIElements);
	} 
}

Using callback in above scenario is not a good approach. Rather use RxJS Observable to respond to data change.

Callback in JavaScript

In vanilla JS code, callback functions exist in the form of timeout functions or interval functions. e.g. In this code, we are calling a JavaScript function setTimeout() which will wait for 2 seconds and then call another function named callback().

console.log("Before function call");

setTimeout(callback, 2000);		//Async function call through setTimeout() method

function callback() {
	console.log("Callback function called");
}

console.log("After function call");

//Output

Before function call
After function call
Callback function called	//After 2 seconds delay

Drop me your questions in comments section.

Happy Learning !!

1 Comment
Newest
Oldest Most Voted
Inline Feedbacks
View all comments

Comments are closed for this article!

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.