A function is a block of code that performs a certain task when called. For example,
// function
function greet(name) {
console.log('Hi' + ' ' + name);
}
greet('Peter'); // Hi Peter
In the above program, a string value is passed as an argument to the greet()
function.
In JavaScript, you can also pass a function as an argument to a function. This function that is passed as an argument inside of another function is called a callback function. For example,
// function
function greet(name, callback) {
console.log('Hi' + ' ' + name);
callback();
}
// callback function
function callMe() {
console.log('I am callback function');
}
// passing function as an argument
greet('Peter', callMe);
输出
Hi Peter I am callback function
In the above program, there are two functions. While calling the greet()
function, two arguments (a string value and a function) are passed.
The callMe()
function is a callback function.
Callback Function 的好处
使用回调函数的好处是,你可以等待前一个函数调用的结果,然后再执行另一个函数调用。
在这个例子中,我们将使用 setTimeout()
方法来模拟需要时间的程序执行,例如来自服务器的数据。
示例:带 setTimeout() 的程序
// program that shows the delay in execution
function greet() {
console.log('Hello world');
}
function sayName(name) {
console.log('Hello' + ' ' + name);
}
// calling the function
setTimeout(greet, 2000);
sayName('John');
输出
Hello John Hello world
正如你所知,setTimeout() 方法会在指定时间后执行一段代码。
在这里,greet()
函数将在 2000 毫秒(2 秒)后调用。在此等待期间,将执行 sayName('John');
。这就是为什么 Hello John 会在 Hello world 之前打印出来。
上述代码是异步执行的(第二个函数;sayName()
不等待第一个函数;greet()
完成)。
示例:使用回调函数
在上面的例子中,第二个函数并不等待第一个函数完成。但是,如果你想在执行下一条语句之前等待前一个函数调用的结果,你可以使用回调函数。例如,
// Callback Function Example
function greet(name, myFunction) {
console.log('Hello world');
// callback function
// executed only after the greet() is executed
myFunction(name);
}
// callback function
function sayName(name) {
console.log('Hello' + ' ' + name);
}
// calling the function after 2 seconds
setTimeout(greet, 2000, 'John', sayName);
输出
Hello world Hello John
在上面的程序中,代码是同步执行的。sayName()
函数作为参数传递给 greet()
函数。
setTimeout()
方法仅在 2 秒后执行 greet()
函数。但是,sayName()
函数会等待 greet()
函数的执行。
注意:当您必须等待需要时间的结果时,回调函数很有用。例如,来自服务器的数据,因为数据到达需要时间。
另请阅读