JavaScript Callbacks Functions are an important concept that you must understand to be a successful JavaScript developer. But I believe that after reading this article, you will be able to overcome all the obstacles you faced before using callback methods.
Before we begin, we must first ensure that our understanding of functions is solid.
A function is a logical building block with a set of code inside it to perform a specific task. Functions actually allow you to write code in a more organized way for ease of debugging and maintenance. Functions also allow code reuse.
You only need to define the function once and then call it when needed instead of writing the same code again and again.
Now, let’s see how to declare a function in javascript.
Using constructor of function: In this method, function is created with the help of constructor of "function". Technically speaking, this method is less efficient than using function expression syntax and function declaration statement syntax to declare functions.
Use function expressions: Usually this method is the same as variable assignment. In short, the function body is treated as an expression, and that expression is assigned to a variable. Functions defined using this syntax can be named or anonymous functions.
A function without a name is called an anonymous function. An anonymous function is self-calling, which means it automatically calls itself. This behavior is also called an immediately invoked function expression (IIFE).
In the function body, the function must return a value to the caller. The function will stop executing after encountering a return statement. Inside the function, parameters will act as local variables.
Similarly, variables declared inside a function are local variables of the function. Local variables can only be accessed within that function, so variables with the same name can be easily used in different functions.
The previously declared function will be called in any of the following situations:
()
operator calls this function.
According to MDN's description: A callback function is a function that is passed as a parameter to another function, and then the callback function is called inside the external function to complete a certain operation.
Let me explain it in human terms, a callback function is a function that will be executed as soon as another function completes execution. A callback function is a function that is passed as a parameter to another JavaScript function. This callback function will be executed inside the passed function.
In JavaScript, functions are regarded as a type of object. By a class of objects, we mean that a number, function, or variable can be the same as other entities in the language. As a class of objects, functions can be passed as variables to other functions, and they can be returned from other functions.
Functions that can perform this operation are called higher-order functions. Callback functions are actually a pattern. The word "pattern" refers to a certain proven approach to solving common problems in software development. It is best to use the callback function as a callback pattern.
Client-side JavaScript runs in the browser, and the browser's main process is a single-threaded event loop. If we try to perform a long-running operation in a single-threaded event loop, the process will be blocked. Technically this is bad because the process stops processing other events while waiting for the operation to complete.
For example, the alert
statement is considered one of the blocking codes in javascript in the browser. If you run alert, you will not be able to interact in the browser until you close the alert dialog window. To prevent blocking long-running operations, we use callbacks.
Let’s dig a little deeper so you know exactly in which case callbacks are used.
In the above code snippet, the getMessage()
function is executed first, and then displayMessage()
is executed. Both display a message in the browser's console window, and both execute immediately.
In some cases, some code will not be executed immediately. For example, if we assume that the getMessage()
function performs an API call, the request must be sent to the server and wait for the response. How should we deal with this?
Instead of telling you the syntax of JavaScript callback functions, I think it would be better to implement the callback function in the previous example. The modified code snippet is shown in the screenshot below.
#In order to use the callback function, we need to perform some kind of task that cannot display the result immediately. To simulate this behavior, we use JavaScript’s setTimeout()
function. The function pauses for two seconds and then displays the message "Hi, there" in the console window.
The "displayed message" will be displayed in the browser's console window. In this case, first, we need to wait for the getMessage()
function. After successfully executing this function, execute the displayMessage()
function.
Let me explain what is happening behind the scenes in the previous example.
As you can see from the previous example, in the getMessage()
function, we passed two parameters. The first parameter is the msg
variable, which is displayed in the browser's console window, and the second parameter is the callback function.
Now, you may be wondering why callback functions are passed as parameters - to implement callback functions, we must pass a function as a parameter to another function.
After getMessage()
completes its task, we will call the callback function. Later, when the getMessage()
function is called, the reference is passed to the displayMessage()
function, which is the callback function.
Note that when calling the getMessage()
function, we only pass its reference to the displayMessage()
function. That's why you won't see the function call operator next to it, the ()
symbol.
JavaScript is considered a single-threaded scripting language. Single threading means JavaScript executes one block of code at a time. While JavaScript is busy executing one block, it cannot move to the next block.
In other words, we can think of JavaScript code as always blocking in nature. But this blocking nature prevents us from writing code in some cases where we have no way to get the result immediately after performing some specific task.
The tasks I'm talking about include situations where:
In order to handle these situations, asynchronous code must be written, and callback functions are one way to handle these situations. So essentially, the callback function is asynchronous.
Callback hell occurs when multiple asynchronous functions are executed one after another. It is also known as the Pyramid of Doom.
Suppose you want to get a list of all Github users. Then search for top contributors to JavaScript libraries among users. Then, you want to get the details of the person named John among the users.
To implement this functionality with the help of callbacks, the code should look like this:
http.get('https://api.github.com/users', function(users) { /* Display all users */ console.log(users); http.get('https://api.github.com/repos/javascript/contributors?q=contributions&order=desc', function(contributors) { /* Display all top contributors */ console.log(contributors); http.get('https://api.github.com/users/Jhon', function(userData) { /* Display user with username 'Jhon' */ console.log(userData); }); }); });
From the above code snippet, you can see that the code becomes more difficult to understand and difficult to maintain. and modifications. This is caused by the nesting of callback functions.
Several techniques can be used to avoid callback hell, as shown below.
Let's talk about how to avoid callback hell with the async.js library.
According to the async.js official website: Async is a tool module that provides direct, powerful functions to use asynchronous JavaScript.
Async.js provides about 70 functions in total. For now, we will discuss only two of them, async.waterfall()
and async.series()
.
This function is useful when you want to run certain tasks one after another and then pass the results from the previous task to the next. It takes a "task" array of functions and a final "callback" function that will be called after all functions in the "task" array have completed, or after the "callback" has been called with an error object.
var async = require('async'); async.waterfall([ function(callback) { /* Here, the first argument value is null, it indicates that the next function will be executed from the array of functions. If the value was true or any string then final callback function will be executed, other remaining functions in the array will not be executed. */ callback(null, 'one', 'two'); }, function(param1, param2, callback) { // param1 now equals 'one' and param2 now equals 'two' callback(null, 'three'); }, function(param1, callback) { // param1 now equals 'three' callback(null, 'done'); } ], function (err, result) { /* This is the final callback function. result now equals 'done' */ });
当你要运行一个函数然后在所有函数成功执行后需要获取结果时,它很有用。 async.waterfall()
和 async.series()
之间的主要区别在于, async.series()
不会将数据从一个函数传递到另一个函数。
async.series([ function(callback) { // do some stuff ... callback(null, 'one'); }, function(callback) { // do some more stuff ... callback(null, 'two'); } ], // optional callback function(err, results) { // results is now equal to ['one', 'two'] });
用技术术语来说,闭包是捆绑在一起的函数的组合,引用了其周围的状态。
简而言之,闭包允许从内部函数访问外部函数的作用域。
要使用闭包,我们需要在一个函数内部定义另一个函数。然后,我们需要将其返回或传给另一个函数。
从概念上讲,回调类似于闭包。回调基本上是把一个函数作为另一个函数的用法。
希望本文能消除你对 javascript 回调函数的所有疑问。如果你觉得这篇文章有帮助,请与他人分享。
原文地址:https://dzone.com/articles/javascript-callback-functions-in-depth-guide-for-2
为了保证的可读性,本文采用意译而非直译。
更多编程相关知识,请访问:编程教学!!
The above is the detailed content of Detailed explanation of callback functions in JavaScript. For more information, please follow other related articles on the PHP Chinese website!