Home > Web Front-end > JS Tutorial > body text

Detailed explanation of callback functions in JavaScript

青灯夜游
Release: 2020-12-14 17:56:33
forward
4243 people have browsed it

Detailed explanation of callback functions in JavaScript

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.

  1. 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.

  2. 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).

  3. 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.

Detailed explanation of callback functions in JavaScript

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.

Detailed explanation of callback functions in JavaScript

#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);
    });
  });
});
Copy after login

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.

  1. Use promise
  2. With async-await
  3. 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'
    */
});
Copy after login

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']
});
Copy after login

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!

Related labels:
source:segmentfault.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!