JavaScript是一个单线程应用程序,如果我们继续将该线程用于所有任务,用户将最终等待阻碍用户体验的其他任务。为了解决这个问题,我们进行了异步编程。
TypeScript支持回调函数,使您的程序异步。回调函数是一个在一些异步处理完成后被调度的函数。回调函数作为参数传递给另一个函数,允许在异步处理完成时调用它们。
通常,callback
在长时间运行的过程(例如从在线REST API获取数据)之后,您将进行函数调用。我们来看一个这种用法的例子。
employee.ts:
export class Employee {
constructor(public id: number) {
}
}
在服务类中,您可以创建可以接受function
类型参数的方法。在处理完请求的方法完成后,它将callback
使用需要传递的数据执行该函数。
app.service.ts
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);
});
}
}
在组件文件中,创建callback
在成功完成服务调用后需要执行的功能。
app.component.ts
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);
}
}
在上面的场景中使用回调不是一个好方法。而是使用RxJS Observable来响应数据更改。
在vanilla JS代码中,回调函数以超时函数或区间函数的形式存在。例如,在这段代码中,我们调用一个JavaScript函数setTimeout()
,它将等待2秒,然后调用另一个名为的函数callback()
。
JavaScript中的回调函数
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
http://blog.xqlee.com/article/452.html