This article gives a brief introduction to the concept and usage of callback functions in the JavaScript programming language.
本文簡要介紹了JavaScript編程語言中的回調函數的概念和用法。
函數就是對象 (Functions are Objects)
The first thing we need to know is that in Javascript, functions are first-class objects. As such, we can work with them in the same way we work with other objects, like assigning them to variables and passing them as arguments into other functions. This is important, because it’s the latter technique that allows us to extend functionality in our applications.
我們需要知道的第一件事是,在Javascript中,函數是一流的對象。 這樣,我們可以像處理其他對象一樣使用它們,例如將它們分配給變量并將它們作為參數傳遞給其他函數。 這很重要,因為后一種技術使我們能夠擴展應用程序中的功能。
回調函數 (Callback Functions)
A callback function is a function that is passed as an argument to another function, to be “called back” at a later time. A function that accepts other functions as arguments is called a higher-order function, which contains the logic for when the callback function gets executed. It’s the combination of these two that allow us to extend our functionality.
回調函數是一個作為參數傳遞給另一個函數的函數,以后將被“回調”。 接受其他函數作為參數的函數被稱為高階函數 ,其包含當所述回調函數被執行為邏輯。 兩者的結合使我們能夠擴展功能。
To illustrate callbacks, let’s start with a simple example:
為了說明回調,讓我們從一個簡單的示例開始:
function createQuote(quote, callback){ var myQuote = "Like I always say, " + quote;callback(myQuote); // 2
}function logQuote(quote){console.log(quote);
}createQuote("eat your vegetables!", logQuote); // 1// Result in console:
// Like I always say, eat your vegetables!
In the above example, createQuote
is the higher-order function, which accepts two arguments, the second one being the callback. The logQuote
function is being used to pass in as our callback function. When we execute the createQuote
function (1), notice that we are not appending parentheses to logQuote
when we pass it in as an argument. This is because we do not want to execute our callback function right away, we simply want to pass the function definition along to the higher-order function so that it can be executed later.
在上面的示例中, createQuote
是高階函數,它接受兩個參數,第二個參數是回調。 logQuote
函數被用作我們的回調函數。 當我們執行createQuote
函數(1)時 ,請注意,當我們將logQuote
作為參數傳遞時,沒有在logQuote
后面加上括號。 這是因為我們不想立即執行回調函數,我們只想將函數定義傳遞給高階函數,以便以后可以執行。
Also, we need to ensure that if the callback function we pass in expects arguments, that we supply those arguments when executing the callback (2). In the above example, that would be the callback(myQuote);
statement, since we know that logQuote
expects a quote to be passed in.
另外,我們需要確保如果傳入的回調函數期望參數,那么在執行回調(2)時我們將提供這些參數。 在上面的示例中,這將是callback(myQuote);
語句,因為我們知道logQuote
希望傳遞一個報價。
Additionally, we can pass in anonymous functions as callbacks. The below call to createQuote
would have the same result as the above example:
此外,我們可以將匿名函數作為回調傳遞。 以下對createQuote
調用將具有與以上示例相同的結果:
createQuote("eat your vegetables!", function(quote){ console.log(quote);
});
Incidentally, you don’t have to use the word “callback” as the name of your argument, Javascript just needs to know that it’s the correct argument name. Based on the above example, the below function will behave in exactly the same manner.
順便說一句,你不必用“回撥”作為參數的名稱,使用Javascript只需要知道它是正確的參數名稱。 根據上面的示例,下面的函數將以完全相同的方式運行。
function createQuote(quote, functionToCall) { var myQuote = "Like I always say, " + quote;functionToCall(myQuote);
}
為什么要使用回調功能? (Why use Callback functions?)
Most of the time we are creating programs and applications that operate in a synchronous manner. In other words, some of our operations are started only after the preceding ones have completed. Often when we request data from other sources, such as an external API, we don’t always know when our data will be served back. In these instances we want to wait for the response, but we don’t always want our entire application grinding to a halt while our data is being fetched. These situations are where callback functions come in handy.
大多數時候,我們正在創建以同步方式運行的程序和應用程序。 換句話說,我們的某些操作僅在上述操作完成后才開始。 通常,當我們從其他來源(例如外部API)請求數據時,我們并不總是知道何時將數據送回。 在這些情況下,我們希望等待響應,但是我們并不總是希望在獲取數據時整個應用程序停止運行。 在這些情況下,回調函數非常有用。
Let’s take a look at an example that simulates a request to a server:
讓我們看一個模擬對服務器請求的示例:
function serverRequest(query, callback){setTimeout(function(){var response = query + "full!";callback(response);},5000);
}function getResults(results){console.log("Response from the server: " + results);
}serverRequest("The glass is half ", getResults);// Result in console after 5 second delay:
// Response from the server: The glass is half full!
In the above example, we make a mock request to a server. After 5 seconds elapse the response is modified and then our callback function getResults
gets executed. To see this in action, you can copy/paste the above code into your browser’s developer tool and execute it.
在上面的示例中,我們向服務器發出了模擬請求。 5秒鐘后,將修改響應,然后執行我們的回調函數getResults
。 要查看實際效果,您可以將以上代碼復制/粘貼到瀏覽器的開發人員工具中并執行。
Also, if you are already familiar with setTimeout
, then you’ve been using callback functions all along. The anonymous function argument passed into the above example’s setTimeout
function call is also a callback! So the example’s original callback is actually executed by another callback. Be careful not to nest too many callbacks if you can help it, as this can lead to something called “callback hell”! As the name implies, it isn’t a joy to deal with.
另外,如果您已經熟悉setTimeout
,那么您一直都在使用回調函數。 傳遞到上述示例的setTimeout
函數調用中的匿名函數參數也是回調! 因此,該示例的原始回調實際上是由另一個回調執行的。 如果可以幫助,請注意不要嵌套太多回調,因為這可能會導致“回調地獄”! 顧名思義,處理它并不是一件愉快的事情。
翻譯自: https://www.freecodecamp.org/news/what-is-a-callback-function-in-javascript/