javascript
什么是JavaScript中的回调函数?
This article gives a brief introduction to the concept and usage of callback functions in the JavaScript programming language.
本文簡要介紹了JavaScript編程語言中的回調(diào)函數(shù)的概念和用法。
函數(shù)就是對象 (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中,函數(shù)是一流的對象。 這樣,我們可以像處理其他對象一樣使用它們,例如將它們分配給變量并將它們作為參數(shù)傳遞給其他函數(shù)。 這很重要,因為后一種技術(shù)使我們能夠擴展應用程序中的功能。
回調(diào)函數(shù) (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.
回調(diào)函數(shù)是一個作為參數(shù)傳遞給另一個函數(shù)的函數(shù),以后將被“回調(diào)”。 接受其他函數(shù)作為參數(shù)的函數(shù)被稱為高階函數(shù) ,其包含當所述回調(diào)函數(shù)被執(zhí)行為邏輯。 兩者的結(jié)合使我們能夠擴展功能。
To illustrate callbacks, let’s start with a simple example:
為了說明回調(diào),讓我們從一個簡單的示例開始:
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是高階函數(shù),它接受兩個參數(shù),第二個參數(shù)是回調(diào)。 logQuote函數(shù)被用作我們的回調(diào)函數(shù)。 當我們執(zhí)行createQuote函數(shù)(1)時 ,請注意,當我們將logQuote作為參數(shù)傳遞時,沒有在logQuote 后面加上括號。 這是因為我們不想立即執(zhí)行回調(diào)函數(shù),我們只想將函數(shù)定義傳遞給高階函數(shù),以便以后可以執(zhí)行。
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.
另外,我們需要確保如果傳入的回調(diào)函數(shù)期望參數(shù),那么在執(zhí)行回調(diào)(2)時我們將提供這些參數(shù)。 在上面的示例中,這將是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:
此外,我們可以將匿名函數(shù)作為回調(diào)傳遞。 以下對createQuote調(diào)用將具有與以上示例相同的結(jié)果:
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.
順便說一句,你不必用“回撥”作為參數(shù)的名稱,使用Javascript只需要知道它是正確的參數(shù)名稱。 根據(jù)上面的示例,下面的函數(shù)將以完全相同的方式運行。
function createQuote(quote, functionToCall) { var myQuote = "Like I always say, " + quote;functionToCall(myQuote); }為什么要使用回調(diào)功能? (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.
大多數(shù)時候,我們正在創(chuàng)建以同步方式運行的程序和應用程序。 換句話說,我們的某些操作僅在上述操作完成后才開始。 通常,當我們從其他來源(例如外部API)請求數(shù)據(jù)時,我們并不總是知道何時將數(shù)據(jù)送回。 在這些情況下,我們希望等待響應,但是我們并不總是希望在獲取數(shù)據(jù)時整個應用程序停止運行。 在這些情況下,回調(diào)函數(shù)非常有用。
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.
在上面的示例中,我們向服務器發(fā)出了模擬請求。 5秒鐘后,將修改響應,然后執(zhí)行我們的回調(diào)函數(shù)getResults 。 要查看實際效果,您可以將以上代碼復制/粘貼到瀏覽器的開發(fā)人員工具中并執(zhí)行。
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.
另外,如果您已經(jīng)熟悉setTimeout ,那么您一直都在使用回調(diào)函數(shù)。 傳遞到上述示例的setTimeout函數(shù)調(diào)用中的匿名函數(shù)參數(shù)也是回調(diào)! 因此,該示例的原始回調(diào)實際上是由另一個回調(diào)執(zhí)行的。 如果可以幫助,請注意不要嵌套太多回調(diào),因為這可能會導致“回調(diào)地獄”! 顧名思義,處理它并不是一件愉快的事情。
翻譯自: https://www.freecodecamp.org/news/what-is-a-callback-function-in-javascript/
總結(jié)
以上是生活随笔為你收集整理的什么是JavaScript中的回调函数?的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 梦到下雨是什么征兆周公解梦
- 下一篇: 梦到锅碗瓢盆什么意思