"In computer programming, a callback is a piece of executable codethat is passed as an argument to other code, which is expected tocall back (execute) the argument at some convenient time. Theinvocation may be immediate as in a synchronous callback, or itmight happen at a later time as in an asynchronous callback."
在计算机编程中,callback是作为参数传递给其他代码的一段可执行代码,其他代码将在某个方便的时间调用(执行)参数。调用可能是立即的,就像在同步回调中一样,或者它可能在稍后的时间发生,就像在异步回调中一样。
而callback function(回调函数)是作为参数传递给另一个函数的函数,然后在外部函数中调用该函数来完成某种例程或操作。
function greeting(name) {
alert('Hello ' + name);
}
function processUserInput(callback) {
var name = prompt('Please enter your name.');
callback(name);
}
processUserInput(greeting);
上面的示例是一个callback function,因为它是立即执行的。但是callback通常用于在异步操作完成后继续执行代码-这些称为异步回调。例如,我们使用GoogleMaps API和地理定位API来显示设备当前位置的地图。由于从其GPS获取设备的坐标是异步的(我们不知道数据将在什么时候返回),Geoloces.CurrentPosition()方法将匿名回调函数作为参数,该函数本身将返回的坐标数据作为参数。此函数仅在返回坐标数据时执行。