Explore Javascript asynchronous programming (1)

Source: Internet
Author: User

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:

 
 
  1. var fn = function(callback) {  
  2.     // do something here  
  3.     ...  
  4.     callback.apply(this, para);  
  5. };  
  6.  
  7. var mycallback = function(parameter) {  
  8.     // do someting in customer callback  
  9. };  
  10.  
  11. // call the fn with callback as parameter  
  12. 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 ).

 
 
  1. setTimeout(function(){  
  2.     console.log("this will be exectued after 1 second!");  
  3. },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 case of asynchronous operations, the function directly returns 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 function? This requires understanding of the Javascript thread model.

Javascript thread model and event-driven

Javascript was initially designed to assist in HTML interaction in browsers. The Browser contains a Javascript engine. The Javscript program runs in this engine and has only one thread. Single-thread can bring many advantages. programmers can be very happy not to consider the annoying problems that need to be faced by multi-thread blocking programming, such as resource synchronization and deadlock. However, many people may ask, since Javascript is single-threaded, how can it be executed asynchronously?
 

This requires understanding of the event-driven event driven Mechanism in the browser. Event drivers are generally implemented through the event loop) and event queue. Assume that the browser has an instance dedicated to event scheduling. This instance can be a thread, which we can call event distribution thread event dispatch thread). The work of this instance is an endless loop, retrieve events from the event queue and process all events associated with the callback function event handler ). Note that the callback function runs in the main Javascript thread, rather than in the event distribution thread, to ensure that the event processing will not be blocked.

Event Loop Code:

 
 
  1. while(true) {  
  2.  var event = eventQueue.pop();  
  3.  if(event && event.handler) {  
  4.      event.handler.execute(); // execute the callback in Javascript thread  
  5.  } else {  
  6.      sleep(); //sleep some time to release the CPU do other stuff  
  7.  }  
  8. }  

Through the event-driven mechanism, we can imagine that the Javascript programming model is to respond to a series of events and execute the corresponding callback function. Many UI frameworks use such models, such as Java Swing ).

Why asynchronous synchronization?

The main purpose of Asynchronization is to handle non-blocking operations. In the process of interacting with HTML, some IO operations are typically Ajax requests and script file loading). If these operations are synchronous, it will block other operations. The user experience is that the page has no response.

In summary, Javascript implements non-blocking IO operations in the form of asynchronous callback functions under the Single-threaded model through the event-driven mechanism.

Challenges of Javascript asynchronous programming

The Javascript single-threaded model has many advantages, but it also brings many challenges.

Code readability

Imagine that if an operation requires multiple non-blocking IO operations and every result is called back, the program may look like this.

 
 
  1. operation1(function(err, result) {  
  2.     operation2(function(err, result) {  
  3.         operation3(function(err, result) {  
  4.             operation4(function(err, result) {  
  5.                 operation5(function(err, result) {  
  6.                     // do something useful  
  7.                 })  
  8.             })  
  9.         })  
  10.     })  
  11. })  

The spaghetti code. Such code is difficult to maintain. In this case, the server side may occur more often.

Process Control

Another problem caused by Asynchronization is process control. For example, I want to access the content of the three websites. When the content of the three websites is obtained, merge the content and send it to the background. The code can be written as follows:

 
 
  1. var urls = ['url1','url2','url3'];  
  2. var result = [];  
  3.  
  4. for (var i = 0, len = urls.length(); i < len; i++ ) {  
  5.     $.ajax({  
  6.         url: urls[i],  
  7.         context: document.body,  
  8.         success: function(){  
  9.           //do something on success  
  10.           result.push("one of the request done successfully");  
  11.           if (result.length === urls.length()) {  
  12.               //do something when all the request is completed successfully  
  13.           }  
  14.         }});  
  15. }  

The code above determines whether all requests are processed by checking the result length. This is an ugly and unreliable method.

Exception and error handling

From the previous example, we can also see that in order to make the program more robust, we also need to add exception handling. In asynchronous mode, exception handling is distributed in different callback functions. We cannot use try... catch Method to handle exceptions, so it is difficult to make it effective and clear.

Better Javascript asynchronous programming
 

"This is the best and worst time"

To solve the problems caused by Javascript asynchronous programming, many developers have made different efforts and provided many different solutions. But how should we choose such a large number of solutions? Let's take a look at all the available solutions.

Promise

Promise objects have been stored in many languages in multiple forms. This term was first used by C ++ engineers in the Xanadu project. The Xanadu Project is a pioneer in Web application projects. Subsequently, Promise was used in E programming language, which inspired Python developers to implement it as a Deferred object of the Twisted framework.

In 2007, Promise caught up with the JavaScript tide. At that time, the Dojo framework was just inspired by the Twisted framework and added an object called dojo. Deferred. At that time, the relatively mature Dojo framework and the initial jQuery framework were fiercely competing for popularity and fame. In 2009, Kris Zyp was inspired by the influence of dojo. Deferred and proposed the Promises/A specification of CommonJS. In the same year, Node. js debuted.

In programming, future, promise, and delay represent the same concept. If Promise is translated into Chinese, it is a "Promise". That is to say, to give you something, I Promise to do it in the future, but now there is nothing. It is used to indicate an object returned by an asynchronous operation. This object is a proxy used to obtain future execution results. The initial value is unknown. Many languages Support Promise.

The core of Promise is its then method. We can use this method to obtain the return value or an exception from an asynchronous operation. Then has two optional parameters, and some implementations are three), which process the success and failure scenarios respectively.

 
 
  1. var promise = doSomethingAync()  
  2. promise.then(onFulfilled, onRejected)  

Asynchronous call of doSomethingAync returns a Promise object promise, and calls the then method of promise to process success and failure. This does not seem to have greatly improved. Callback is still required. However, the difference is that the asynchronous operation has a return value, although this value is only a commitment to the future. Secondly, by using then, programmers can effectively control process exception handling, determine how to use this value from the future.

With support for Promise, nested asynchronous operations can be written as a chain operation:

 
 
  1. operation1().then(function (result1) {  
  2.     return operation2(result1)  
  3. }).then(function (result2) {  
  4.     return operation3(result2);  
  5. }).then(function (result3) {  
  6.     return operation4(result3);  
  7. }).then(function (result4) {  
  8.     return operation5(result4)  
  9. }).then(function (result5) {  
  10.     //And so on  
  11. });  

Promise provides more convenient process control. For example, Promise. all () can solve the need to concurrently execute several asynchronous operations and process all the operations after they are completed.

 
 
  1. var p1 = async1();  
  2. var p2 = async2();  
  3. var p3 = async3();  
  4. Promise.all([p1,p2,p3]).then(function(){  
  5.     // do something when all three asychronized operation finished  
  6. });  

For Exception Handling,

 
 
  1. doA()  
  2.   .then(doB)  
  3.   .then(null,function(error){  
  4.       // error handling here  
  5.   })  


Related Article

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.