Foreword: Recalling the first time I saw the term "callback function", it really made me cry. When all video tutorials talk about a certain knowledge point, they will probably say: "Ah, what should I do here? Here we need to use a callback function...".
Wait, hey, the key is that you haven't talked about what a callback function is!, how do you tell me to continue listening...so I left me alone to watch the next few minutes of the video, but my mind is still Confused about what this "callback function" is.
Note: The prerequisite knowledge for this article is that you need to understand the execution mechanism of href=" https://juejin.cn/post/7172948984145641479 ">JS. I strongly recommend that you familiarize yourself with the prerequisite knowledge points before looking down, because our ultimate goal is to write Promise by hand, but you must master the knowledge points explained before.
1. Function
- Although the basic concept of the callback function has been mentioned in my previous article, in order to introduce the following, I will briefly mention it here again. Let's take a look at MDN 's explanation first.
2. What do you mean? Take our example from the previous chapter. In a setTimeout , print a console.log() to the console after 1 second .
3. Let's tear it down. Let's take a closer look at the following line of code, have you found it? I just changed the declaration of an arrow function into the definition of an anonymous function . In fact, the effects of these two writing methods are exactly the same. (Please don't consider the difference between arrow functions and ordinary functions for now)
In this case, the above anonymous function and arrow function are collectively referred to as the callback function of the function setTimeout . The thing you definitely need to understand is that setTimemout is also a function! A single function cannot be called a callback function, and the concept of a callback function is mutual. So a more precise statement should be:
First, the arrow function and anonymous function here are used as the parameters of setTimout , and then they are called inside setTimout, and finally the arrow function and anonymous function are called the callback function of setTimout .
4. I found that there are actually many novices who do not understand the different declaration methods of functions, which is why you are confused. Let's first talk about the three commonly used definitions of functions.
Although the execution results of these three functions are the same here, their differences are not small. A function is declared using the function keyword. is called a function declaration. The following two methods are called function expressions .
5. Although we all use "()" to call in the method of use, there are still differences between them. One of the most important differences is that when a function is defined using a function declaration , the variable will be raised by the js parser before the code starts to execute. Functions defined using function expressions are not hoisted. What does that mean?
You will find that we can actually hello
use this function before defining the function. Both of the following two functions reported an error called before assignment.
6. Here we extend another knowledge point. Before we define hello
a function, we first define a variable name
.
Although it seems to be declared before the function here, name
the declaration of this variable is actually before the variable.hello
hello
name
7. The reason is simply described: After the js parser finds your .js
file, it will first look for the function names declared in use, then save these function names in an object, and create a reference in advance to -- > points to the function body. The specific details need to be inquired by readers independently, and the focus of this article is not here.function
8. If you understand the above links, then I think you should also understand this way of writing.
So let's strike while the iron is hot and start the next chapter.
2. Data processing method
- We all know that functions are to help us complete some complex logical operations, can be called repeatedly, and functions can pass parameters.
For example, the above function allows us to pass two variables of type number, and then the function will return the sum of these two numbers to us.
2. ok, the above content is very simple, I think everyone should understand. If there is no delay in the data transmission in our daily dealings with the backend, then naturally it will be very convenient for us to process the data. What does that mean? Assuming we send a request to the backend to obtain data , this process is completed in an instant, then we can write from top to bottom along our ideas very smoothly.
Like the function just written above, you can understand that we have requested a piece of data from the backend server, and the data is returned in an instant, so we can return the data . Then use a variable to accept it below, and then perform some calculations.
3. As mentioned in the previous article. Unfortunately, when we are performing some tasks that may take a certain amount of time to complete, it is impossible to complete them synchronously. It is very undesirable to block the execution of the entire subsequent code because of one line of code.
4. Here we simply simulate a scene.
We define a generic object data
to simulate the data that the backend will pass to us. We assume that this data may take 1s to return. We may naturally think, isn't that the same as before, setTimeout
wouldn't it be enough to return here.
You can think about the above code first, userData
will you get the correct data
value?
5. Unfortunately, we cannot get the return value of the asynchronous function immediately in the synchronous code.
So what is the reason for the result of the above code? Why is it undefined
? We analyze step by step.
3. Clarify thoughts
- When the code with the yellow line below is executed. In the next step, we need to jump
getData
into the function body for analysis.
2. When entering this function, the first step is to execute the setTimeout function. (I will emphasize again and again here that setTimeout itself is an ordinary function, nothing special.)
3. But the setTimeout function will push the received callback function to the task queue for queuing. What? You don't see the callback function? Isn't this one of the ways of declaring the function mentioned at the beginning of the article? Arrow function ? How did you forget it so quickly? Consciously turn back to the top and read it again⏰.
4. Immediately after getData函数
the execution is completed, at a glance, the function itself has no return value, so the default return value is undefined .
5. Special attention is required here! If we write it here return语句
, this can be regarded as getData函数的
the return value.
In our data
case, it is the return value of the callback function of setTimout , so it's no wonder you can get it.
6. What should I do then? Let's continue reading.
4. Callback function
- Don't worry about looking down, after the above three links, let's do a small test first.
Did you understand the code above? (The following is the execution result)
It doesn't matter if you are not particularly clear about the execution result. At this point, I just hope that you can understand the following line of code, at least in terms of writing, you know why you can write it like this
If you haven't figured it out for a while, I strongly recommend that you at least go back and savor the first title function again , and read it carefully this time.
2. If you understand, congratulations, you are one step closer to understanding this term. Next we modify the code a little bit.
3. The above code looks mysterious at first glance, don't worry, let's analyze it slowly. The first is a function that modifyData函数
we set in advance to process back-end data. (The premise is if we can get the data given to us by the backend) .
4. Since we have no way to get the data in the synchronization function and then process it, then we simply give the back-end code function getData
a parameter in advance.
A processing function that we set up in advance. When the callback function of setTimeout gets the data, it will help us execute this function, that ismodifyData 函数
. Then pass data as a parameter tomodifyData函数
.
5. We print the value before and after modification in the callback function of setTimout .
6. We will find that if all our subsequent codes are processed in the callback function, the requirements can be perfectly realized. That is to say, we can get the data transmitted from the back end and process it into the data we want.
epilogue
Here we will not introduce the concept of returning to hell, I am afraid that the readers of the capital will indeed be confused. I will introduce this concept before handwriting Promise . I hope readers can understand the above code carefully. Once you learn these concepts, you will see a different js world from before.