HowToDoInJava

  • Java 8
  • Regex
  • Concurrency
  • Best Practices
  • Spring Boot
  • JUnit5
  • Interview Questions

TypeScript async callback with parameters

By Lokesh Gupta | Filed Under: TypeScript

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 !!

About Lokesh Gupta

Founded HowToDoInJava.com in late 2012. I love computers, programming and solving problems everyday. A family guy with fun loving nature. You can find me on Facebook, Twitter and Google Plus.

Ask Questions & Share Feedback Cancel reply

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

*Want to Post Code Snippets or XML content? Please use [java] ... [/java] tags otherwise code may not appear partially or even fully. e.g.
[java] 
public static void main (String[] args) {
...
}
[/java]

Search Tutorials

  • Email
  • Facebook
  • RSS
  • Twitter

TypeScript Tutorial

  • TypeScript – Introduction
  • TypeScript – Types
  • TypeScript – Union Types
  • TypeScript – String Literal Types
  • TypeScript – var, let and const
  • TypeScript – Template Strings
  • TypeScript – Arithmetic Operators
  • TypeScript – Logical Operators
  • TypeScript – Comparison Operators
  • TypeScript – ‘for…of’ Loop
  • TypeScript – Spread Operator
  • TypeScript – Arrays
  • TypeScript – Enums
  • TypeScript – Map
  • TypeScript – Set
  • TypeScript – Functions
  • TypeScript – Function Overloading
  • TypeScript – Transpiler
  • TypeScript – Truthy and falsy
  • TypeScript – == vs ===
  • TypeScript – undefined vs null
  • TypeScript – Variable Hoisting
  • TypeScript – tsconfig.json

Popular Tutorials

  • Java 8 Tutorial
  • Core Java Tutorial
  • Java Collections
  • Java Concurrency
  • Spring Boot Tutorial
  • Spring AOP Tutorial
  • Spring MVC Tutorial
  • Spring Security Tutorial
  • Hibernate Tutorial
  • Jersey Tutorial
  • Maven Tutorial
  • Log4j Tutorial
  • Regex Tutorial

Meta Links

  • Advertise
  • Contact Us
  • Privacy policy
  • About Me

Copyright © 2016 · HowToDoInjava.com · All Rights Reserved. | Sitemap