It has been a long time since the last blog post. These months, I started my internship in the company, finished designing and went out to look for apartments. Big four dog’s life is so tiring (sobs face). Back to the blog post itself, I have always been very interested in using Node.js to write some background programs, but I didn’t start to learn the knowledge of Node.js development until I joined the company. Asynchronous programming uses callback functions, so I decided to learn the concept and usage of the callback function seriously

Pull pull Node. Js

Node.js Succinctly is a basic node.js book. Learn about the asynchronous non-blocking nature for which Node.js is famous. So what is asynchronous non-blocking? First of all, we need to understand that JavaScript itself is an event-driven (observer mode) and single-threaded language, and its characteristics are relevant to the context in which JavaScript was born. JavaScript was originally designed to enrich Web interaction, namely DOM manipulation, simple form validation. Similarly, Node.js executes programs that are inherently single-threaded, because JavaScript is also used. (The decision to use JavaScript was made when Node.js was designed for its single-threaded nature.) If a single thread encounters time-consuming operations such as I/O operations, network access will block the execution process behind the thread. Therefore, in order not to block the only execution thread, asynchronous mode is used. The asynchronous approach is to allow time-consuming operations to be done in other threads, let’s call them worker threads. When some time-consuming operation is completed, the result of execution needs to be returned to the main thread. This step is done through the callback function, which is also event-driven. Therefore, we can say that the most direct expression of asynchronous programming is the callback, but the callback function is not directly related to asynchronous/synchronous. For example:

function heavyCompute(n, callback){ let count = 0, i, j; for (i = n; i > 0; --i){ for(j = n; j > 0; --j){ count += 1; } } callback(count); } heavyCompute(10000, function(count){ console.log(count); }); console.log('hello');Copy the code

The results are as follows:

100000000

hello

As you can see, the callback function of the above code still precedes the subsequent code, and you can also see that JavaScript functions are first-class citizens, as they can also be used as function arguments. This method is called synchronous callbacks, and asynchronous callbacks are similar to the action of clicking a button to trigger a popup when writing a page, as follows:

. let btn = document.getElementByID('myButton'); btn.addEventListen('click',function(ev){ console.log(ev.target); }); .Copy the code

What is a callback function

More broadly, programming is divided into system programming and application programming. System programming is about writing libraries that are relatively close to the hardware. And application programming is to use all kinds of libraries written to write a certain function of the program. System programmers leave some interfaces, called application Programming interfaces (apis), to the libraries they write for use by the user programmers. So in the abstraction layer diagram, the library is underneath the application.

When the program is running, the application will normally call library functions from time to time through the API. There may be situations where some library functions require the application to pass it a function to call at the appropriate time, having done its job. The function that is passed in and then called is called a callback function.

As you can see, the callback function is usually at the same abstraction level as the application (because the application layer determines what callback function is passed in). The so-called “callback” is a process in which a higher-level function calls a lower-level function, or library function, and the lower-level function calls the higher-level function back.

Take the process of paying for a meal in a restaurant as an analogy: when the customer calls the waiter to pay, the waiter calculates the total price according to the order in hand and then tells the customer how much to pay. In this process, the guest asking the waiter to pay the bill is just like the high-level function of the application program calling the low-level function, where the application program refers to the context in which the guests at the table want to pay the bill, and the low-level function is the process in which the waiter calculates the total price. The waiter calculates the total price and then tells the guest, which is similar to the low-level function calling the high-level function and returning to the context of the guest paying the bill.

Why do we need Callback functions

Callback is a mechanism that provides more flexibility than simple function calls. In addition to the above application scenarios, the above callback mechanism can be implemented anytime, not just between applications and libraries. Therefore, we call the above library functions intermediate functions from here on out. How does the flexibility of the callback mechanism work? We can assume that an intermediate function is logically incomplete without passing in a callback function. In other words, a program can change the behavior of intermediate functions by passing in different callback functions at run time, which is much more flexible than a simple function call. Let’s look at an example written in Python:

even.py

Def double(x): return x * 2 def quadruple(x): return x * 4Copy the code

callback_demo.py

Return an odd number def getOddNumber(k, getEvenNumber): Return 1 + getEvenNumber(k) # def main(): Print (I) print(I) print(I) print(I) print(I) print(I) print(I) quadruple) print(i) if __name__ == "__main__": main()Copy the code

Run callback_demp.py and the output is as follows:

3

5

In the above code, getOddNumber behaves differently if you pass it a different callback, which is the advantage of the callback mechanism.

The intermediate function and the callback function are necessary parts of the callback mechanism, but the starting point of the callback mechanism is often overlooked. It is also the caller of the intermediate function, which in most cases can be identified with the main function of the program. Therefore, the callback mechanism is a tripartite linkage of the initial, intermediate, and callback functions. The initiator function and the callback function cannot be seen as one and the same. Because there are actually two types of callback: blocking and deferred. Blocking, the callback must be called before the initial function returns; Deferred, the callback may be called after the initial function has returned. Therefore, the initiator function and the callback function are not the same thing.

Back in JavaScript, why do we need callback functions? So we also said that JavaScript is an event-driven language. This means that the JavaScript executor will not wait for a response, but will continue executing while listening for other events.

reference

  1. What is a callback? Answer to no. Body – Zhihu
  2. JavaScript: What the heck is a Callback? |Medium
  3. Learn NodeJS in seven days