JavaScript series-synchronous or asynchronous?

Source: Internet
Author: User

From today on, I will occasionally write something about JavaScript, including languages and applications. To form the JavaScript series.
Unless otherwise specified, it is assumed that the JavaScript execution environment is in the browser.
For the first time today, we will discuss synchronization and Asynchronization.

I have searched some JavaScript Information and found that google's results are all about how JavaScript can implement asynchronous code.
Unfortunately, I am wondering how to synchronize JavaScript asynchronous calls (isn't it strange ).

First, let's talk about the Asynchronous Method in JavaScript.
In fact, this problem is frequently encountered. This implementation is also very simple. I won't say much about it.
Give two Codes

SetTimeout method, which allows your code to execute the specified method after the specified time (milliseconds. Run only once.
For example:
Alert (1 );
SetTimeout ("alert (2)", 1000 );
Alert (3 );
When the code is executed to setTimeout, it will continue to execute the following code (alert (3) without being blocked. Execute alert (2) after waiting for 1000ms)
SetInterval method, which allows your code to execute the specified method at a specified time until clearInterval is called.
For example:
Alert (1 );
Timer = setInterval ("alert (2)", 1000 );
Alert (3 );
The code is basically the same as above. The difference is that alert (2) will be executed once every ms until the call
ClearInterval (timer );
We should note that setTimeout and setInterval are both window methods.
We can use it directly, but we still call window. setTimeout window. setInterval in a standard way. I will continue to explain this in the future JavaScript series.

Now let's talk about my problems.
I now use dwr as the AJAX server engine. when calling the dwr method, I need to provide a callback function to accept the server's returned results.
This callback method will not be blocked. In this case, browser starts another off-the-shelf processing.
This is easy to understand, because the execution time of the dwr method is unpredictable. If the call is blocked at this time, the server takes a long time to process it. Then the browser will die here. It is unacceptable from the perspective of user experience.
The example code here is

...
ServerHandler. getString ("Weiming", function (str) {// "Weiming" is a parameter sent back to the server.
Alert (str );
}); // ServerHandler is the server method interface provided by dwr. For details, see the dwr website.
Alert (1 );
In the execution process, alert (1) is executed first, and then alert (str) is executed after an unexpected time ).
If a simple call, such as hello world, is successful.
However, if the series of dwr functions that I want to execute have a forward and backward order, for example, the subsequent execution requires the previous returned results, the execution sequence cannot be guaranteed by the simple code writing sequence.
Var myID = null;
ServerHandler. getID (function (id ){
MyID = id; // unexpected execution time
});

ServerHandler. getUserWithID (myID, function (name ){
/*
At this time, there is no value for myID, because the above myID = id code will be executed after a period of time.
*/
Alert ("hello:" + name );
});

For example, this code will cause errors. How can this problem be solved?
The simplest implementation method is callback function nesting.
...
ServerHandler. getID (function (id ){
ServerHandler. getUserWithID (id, function (name ){
Alert ("hello:" + name );
}
});
In this way, we can ensure the order in which multiple dwr methods are called. This seems to solve the problem. But not perfect.
The reason is that when we use JavaScript and Browser as an operating platform and a logical business platform (AJAX applications will be mentioned later in the JavaScript series ), instead of simply presenting the platform. Such callback function Nesting is difficult to control.
This is a method that I initially pointed out to require synchronous asynchronous calls.

In the end, my solutions at the company were like this.
Write a semaphore class (JavaScript object-oriented will be explained later). When I need to execute a method, I apply for a part of the semaphore.
Put the method to be executed into the semaphore queue for waiting. Wait until the method (if any) is executed before execution.
The semaphore will be passed into the execution method as a parameter, so that this method can decide whether to release the semaphore or continue distribution.
For example
Var s = new Semaphore ();
Var myID = null;
S. p (function (e) {// put the method into the semaphore queue
ServerHandler. getID (function (id ){
MyID = id;
S. v (); // release the semaphore
}
});

S. p (function (e) {// put the second method into the semaphore queue. This method will be executed only after the current s. v () is executed.
ServerHandler. getName (myID, function (name) {// at this time, you can ensure that myID has a value
Alert ("Hello:" + name );
S. v ();
})
})

Here is a brief description of the semaphore method.
Semaphores also support the creation of self-semaphores. If a sub-semaphores are created, the parent semaphores must be executed only after all the children with the semaphores are returned.
Because the copyright of the Code is owned by the company, I am sorry. At present, the complete semaphore implementation cannot be provided.
If I have time at the next end, I will provide a version of my implementation.

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.