Explore Javascript asynchronous programming (1)
The problems caused by asynchronous programming are not obvious in the client Javascript. However, as the server Javascript becomes more and more widely used, a large number of asynchronous IO operations make the problem obvious. Many different methods can solve this problem. This article discusses some methods, but they are not in-depth. You need to select a method that suits your needs.
In my previous blog, I briefly discussed the similarities and differences between Python and Javascript. In fact, asynchronous programming as a programming language Javascript is a very interesting topic worth discussing.
Introduction to JavaScript asynchronous programming
Callback Function and asynchronous execution
The so-called Asynchronization refers to the asynchronous execution of callback functions instead of directly returning execution results.
Let's first look at what the callback function is:
- var fn = function(callback) {
- // do something here
- ...
- callback.apply(this, para);
- };
-
- var mycallback = function(parameter) {
- // do someting in customer callback
- };
-
- // call the fn with callback as parameter
- fn(mycallback);
A callback function is actually a function provided by the user. It is usually provided in the form of parameters. Callback functions are not necessarily executed asynchronously. In the preceding example, the callback function is executed synchronously. Callback is supported in most languages. C ++ can use function pointers or callback objects. Java generally uses callback objects.
In Javascript, there are many asynchronous calls executed by callback functions, such as setTimeout) or setInterval ).
- setTimeout(function(){
- console.log("this will be exectued after 1 second!");
- },1000);
In the preceding example, setTimeout is returned directly. An anonymous function is asynchronously triggered and executed after 1000 milliseconds, which may not be guaranteed to be 1000 milliseconds. This completes the operations on the print console. That is to say, in the context of asynchronous operations, the function returns directly and gives control to the callback function. The callback function will be scheduled for execution in a later time segment. So why does it need to be asynchronous? Why cannot I directly complete the operation in the current number of letters? This requires understanding of the Javascript thread model.