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.
Quick Review: JavaScript Functions
What are functions?
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.
Declaring a function
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).
-
Use function declaration: This method is the old-school method commonly used in JavaScript. After the keyword "function" you must specify the name of the function. Later, if the function accepts multiple arguments or arguments, they need to be mentioned as well. Although this part is completely optional.
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.
Calling a function
The previously declared function will be called in any of the following situations:
- When an event occurs, e.g. , the user clicks a button, or the user selects some option from a drop-down list, etc.
- When calling the function from javascript code.
- This function can be called automatically, which we have discussed in anonymous function expressions.
()
operator calls this function.
What is a callback 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.
Why we need callbacks
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?
How to use callback functions
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.
How callbacks work
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.
Are Javascript callbacks asynchronous?
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:
- Get data by making API calls to some endpoints.
- Get some resources (for example, text files, image files, binary files, etc.) from the remote server by sending a network request.
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.
Javascript Callback Hell
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.
How to avoid callback hell?
Several techniques can be used to avoid callback hell, as shown below.
- Use promise
- With async-await
- Use async.js library
Use Async.js library
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()
.
async.waterfall()
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.series()
当你要运行一个函数然后在所有函数成功执行后需要获取结果时,它很有用。 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 回调与闭包
闭包
用技术术语来说,闭包是捆绑在一起的函数的组合,引用了其周围的状态。
简而言之,闭包允许从内部函数访问外部函数的作用域。
要使用闭包,我们需要在一个函数内部定义另一个函数。然后,我们需要将其返回或传给另一个函数。
回调
从概念上讲,回调类似于闭包。回调基本上是把一个函数作为另一个函数的用法。
最后的话
希望本文能消除你对 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!

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

WebStorm Mac version
Useful JavaScript development tools

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.