On the understanding of JS's Callback callback function

Source: Internet
Author: User

The processing logic of the callback function is understood:

The so-called callback function processing logic, in fact, is to first freeze the code of the callback function (or understand it as idle), and then put the callback function code into the callback function manager queue.

When the callback function is invoked, the code of the corresponding callback function is removed from the manager queue and executed automatically (the code that activates the callback function) to achieve the asynchronous programming effect.


However, for some actions that must wait for the callback function to be completed, in fact, it will fall into a layer of callback situation. This is also a complex part of the callback function!
In other words, as long as the value you want to get is determined by the callback, then all the code that follows must be written in a callback form, nested layers.
A simple example of a Baidu question:
Problem:
JS callback function problem execution results want to be returned value
function receive ()
{
var re_data;
Client.on (' Data ', function (data) {
Re_data = data;
Console.log (data);
Client.end ();
});
return re_data;
}
The purpose of the receive function is to return the received data, but in a callback, the data value is always executed with a return and then the callback function, so the return value is always undefined, is there any way to resolve it?
Workaround:
Suggest changing your way of thinking, and changing your function receive to a callback:
function receive (callback) {
// ....
Client.on (' Data ', function (data) {
callback (data);
});
}
Then, to call the receive function somewhere else, all the actions after the value obtained by the function are encapsulated in the callback function callback.
For example:
aaaa
Receive (function (data) {
The following code is available for data.
Data .... The treatment of ...
});


another more vivid statement about the callback function:
Context: Suppose a function calls the B function (b function is asynchronous), call function A is the parent function, and the called Function B is a child function.
Callback Function Example: The father let his son do a thing, when finished will give a red envelope (to the son). Then the father went to poop at once.
Examples of analysis:
First, things have to be done before they can be given a red envelope. In addition, the money of the red envelope is of course the father, the son only needs to be completed, the red envelope can be opened. Of course, the son does not know how much money his father will give.
Very simple, huh? In fact, the callback function is the idea of such a child.
Father asked his son to do one thing--the father function called the son's function method. This son's function method is asynchronous, and does not affect the father's next move (poop).
Red Envelopes--the name of the callback function. That is, the callback name. The son just has to be sure to take it apart (execute it). As for what is inside, how much money, son can not control, determined by the father.
The money inside the red envelope--can be understood as the code snippet executed by the callback function. This of course is provided by the father!
After the son is finished, he can remove the red envelopes--the son function is completed, will call the father provided a callback function (that is, split red envelopes, Count money).

Another perspective of image understanding:
The callback function gives the impression of being more realistic. Anyway, call the corresponding function to get the information.
After the information is obtained, what else do you want to do (for example, to notify me proactively after completion), you can write the logic itself into the callback function, let the called function automatically execute the callback function code, complete the process!
Note: It must be noted that, if the function is asynchronous, the entire code is executed asynchronously. Does not affect the order in which the code for the function of the keynote is executed. This is called Async!

now the problem, especially some nested callback functions, how to understand it?
Now let's take a look at the so-called nested asynchronous callback function.
A simple way to understand:
The code of the main function is actually executed in order.
As long as the code encapsulated in the callback function is waiting for the deepest callback function to execute, the code of the previous level of the callback function will be executed one after the other!
Another understanding: I don't need to know how you do it, just tell me when you're done, and tell me the results. I just want the results!
If you want to wait until you know the result to continue to do things, it is to write in waiting for others to tell me after the list of things to do (callback function of things);
If it is something else, such as a poop pee or something, do it right away, without waiting!
As an example:
I want two-tier suppliers to have 2 pieces of coated architectural glass. I do not need to know how this glass is made, how the glass to the first level supplier, how to the level two supplier.
Anyway your level two supplier can provide me with the required glass on it, provided to tell me how much the price, so I am ready to pay you.
-and it's important to note that I've received the architectural glass before I can do the installation of glass and so on.
But, what I want to do when I do it is nothing to do with buying glass.
In fact, the above example is a nested callback function.
Manufacturing process functions:
var make = function (Qty,type,callback) {
Also check the quantity and type of orders received. Some types may not be produced!
Makecheck ();
Manufacturing the required glass according to the number of Qty and type
To go through the production of many processes ...
Factory.makeglass ();
When you're done, call the callback function and the notification is made! Can come to pick up the goods. Of course you have to collect money. is to provide the price to the caller (batch factory price).
var amount=100 dollar
Callback (amount);
}
First-level vendor functions:
var Vendor1 = function (qty,type,callback) {
When receiving an order, repeat the check quantity and type.
Vendor1check ();
Order the factory. The quantity and type to be specified is required. First-level suppliers do not need to know how to make, only need to notify the factory to the goods can
Make (Qty,type,function (amount) {
Factory Manufacturing finished, received the factory's offer, the first supplier of course to make money, so to increase the 10%
var vendoramount=amount*1.1;
Executes the callback function code provided by the father, and notifies the first-tier vendor of what the price is (proactively providing parameters for the callback function).
Callback (Vendoramount);
});
}
Secondary supplier functions:
var Vendor2 = function (qty,type,callback) {
Receive the order, and then check that the quantity and type are correct. Whether this type of glass can be produced.
Vendor2check ();
Secondary suppliers do not need to know where the goods are taken, only need to notify the first-level suppliers to the goods can be
Then order the first class supplier. The quantity and type to be specified is required.
Vendor1 (qty,type,function (amount) {
The goods arrived, received the first level supplier's quotation, here two level supplier certainly must make money, therefore must increase 20%
var vendoramount=amount*1.2;
Executes the external callback function and notifies the user of the price it provides.
Callback (Vendoramount);
});
}

User functions:
The user is the ultimate consumer.
var user = {
The user buys the Glass the function method:
Userbuy:function (Qty,type,callback) {
Check whether the quantity is correct, whether the glass type is needed.
Usercheck ();
The user takes the goods to the level two supplier. It should be noted that after the arrival of the installation and other actions. are written in callback.
Vendor2 (qty,type,function (amount) {//calls the two-level vendor's interface. and write the callback function and know what to do after the price.
It is written here about the execution of the glass after it arrives. It may be 10 days before the execution.
User.receive ();//User Goods receipt
User.check ();//Users check the quality of goods
User.pay (amount);//user Payment
callback;//here executes a callback function, which can be the installation of glass, can even be sent to others and so on. It is up to the caller to decide what to do.
});
},
Meal: function () {xxxxx},
Poop: function () {xxxxx},
Sleep:function () {xxxxx},
}

Based on the function method defined above, a realistic example is simulated:
The user eats in the morning, buys the glass at noon, buys the glass after the order, then pulls a excrement, then sleeps.
Imagine, if you want to wait until the glass to take a crap, it would not be suppressed to death.
----Program Process:
User. Eat ();
Buy Glass
User.userbuy (10, ' coating architectural glass ', function (amount) {
User. Mounting glass ();
});
User. ();//Because the purchase of glass is an asynchronous function, so here to buy the glass request (call buy glass function), immediately can go to poop, a moment does not affect!
User.sleep ();//user poop finished, comfortable, go to bed!

As you can see in the above example, the callback function is actually executed at the layer level. Execute the deepest layer, then go up one after the other.
The execution sequence of the program is executed when the user buys the Glass method:
The execution order of the main function:
Userbuy (how users call to purchase goods) parent
-->vendor2 (method of supplying goods by tier two suppliers) sub-
-->vendor1 (method of delivery of goods by tier-I suppliers) sun
-->make (method of factory manufacturing process) great-grandchildren
and the order in which the code of the callback function written by each main function is executed:
MAKE.CB (The factory is finished, the callback function [executes (parent) first-level vendor-provided code], equivalent to notify the first-level suppliers, the goods have been completed! How much is the price. )
-->VENDOR1.CB (First level supplier confirms that the factory is finished, call the callback function [Execute level two supplier code], notify level two supplier, the goods already have, the price is how much. This time the price has been 10% increase)
It is important to note that it is necessary to wait until the production is complete and to know the actual price provided by the factory before you can increase the fare. So the markup code is offered by Vendor1, but execution is performed by the factory with callback!
-->VENDOR2.CB (Level Two suppliers get the goods, call the callback function [execute the code provided by the user purchase], notify the user, the goods have already, the price is how much. At this time the price added 20%. It's dark! )
-->USERBUY.CB (the user gets the goods, a prior shipment and payment, and calls the callback function [code after the glass arrives, that is, the callback code written when the user.userbuy is called, such as the installation of glass, etc.]. The process is finished! )
As you can see, the order in which the nested callback functions are executed is reverse-stepping.
Each callback function code is only related to its son. After the son finishes, the callback function is automatically executed [the code written by the father].
can also say:
The father invokes the son's method and writes the code to the son to execute the callback function. The code of the son's callback function is provided by the father. The name is callback.

Summary:
The so-called callback function is a function that provides execution code by the calling function, and then executes automatically after the called function is executed. An asynchronous.
In the case of a nested callback function, the callback function that invokes the function embeds the function between the code of the callback function that the called function is running (execution). is the callback function in the callback code. Nested callbacks!

On the understanding of JS's Callback callback function

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.