This is the 19th day of my participation in the August Wenwen Challenge.More challenges in August
Preface:
Hello, everyone, it’s Thursday, beautiful weekend is waving to us, no pain, no gain, hope is in front, let us continue the road of more text, front small white not lost – today to today to introduce what is back to hell.
What is callback hell
There are a lot of pictures of callback hell on the Internet, which sound very esoteric, but are simply nested callback functions. So, what is a callback function?
Callback function:
Passing a function as an argument that the definition of the function will not be executed immediately but will be called at a specific time in the future is called a callback. Note: The callback function does not block execution of the main thread code. For example, the following console print:
Why callbacks are used:
The callback function is used for timer setTimeout and Ajax requests. 1. Under the requirements of specific scenes, we use timers to control a function and trigger it after a specified time; 2. In Sending Ajax, requests and responses between the client and server take time, and we have to wait for the response to complete. These are common scenarios for callback functions.
Why use nested callback functions:
As shown in the figure, we want to read the contents of the three documents in the order of writing. Although the order is A.txt ··> B.txt ···> ··· ·c. TXT, the result is not as expected. This is because the reading of files is asynchronous and does not affect each other.
Just like the 100-meter sprint, who gets to the finish line first is uncertain. In order to achieve the document reading order: A, B, C, we must make the 100-meter race into a relay race, get the baton of the last student, and the next student can enter the race.
After testing, the printed result is the contents of a, B and C files each time. Then, as shown in the figure, the callback functions are layered on top of each other, gradually forming the “callback hell”, although the callback hell changes the execution order of asynchronous functions to synchronous. But such code is very unreadable and maintainable.
Afterword.
This article describes how to solve the nested callback function.