JavaScript Series-Synchronous or asynchronous? _ Practical Tips

Source: Internet
Author: User
Tags semaphore setinterval
Starting today, I'm going to write something about JavaScript on a regular basis, including language, applications, and more. Compose a JavaScript series.
If there are no special instructions, this assumes that the execution environment for JavaScript is in the browser (browser).
For the first time today, let's talk about synchronization and Asynchrony.

Once queried for some JavaScript information, it turns out that Google's results are asking how JavaScript can implement asynchronous code.
And I, unfortunately, query is how to get JavaScript to implement asynchronous invocation synchronization (it's pretty weird).

First, let's talk about asynchronous methods in JavaScript.
In fact, this problem is often encountered. And this implementation is also very simple. I will not say more.
Give two pieces of code

SetTimeout method, he lets your code execute the specified method after a specified time (in milliseconds). Executes only once.
Like what:
Alert (1);
SetTimeout ("Alert (2)", 1000);
Alert (3);
The code continues to execute the following code (Alert (3)) without being blocked when executing to settimeout. Wait for 1000ms to execute alert (2)
SetInterval method, he lets your code execute the specified method every time specified, until the call to Clearinterval
Like what:
Alert (1);
Timer = setinterval ("Alert (2)", 1000);
Alert (3);
The code is basically the same as the above, and the difference is that alert (2) is executed every 1000ms, until the call to
Clearinterval (timer);
We should note that both settimeout and setinterval are window methods.
We can use it directly, but the spec or call Window.settimeout Window.setinterval, and I'll continue to explain this in a later JavaScript series.

Now it's time to talk about the problems I've encountered.
I now use DWR as the AJAX server-side engine, and when I invoke the Dwr method, I need to provide a callback method (callback function) to accept the server's return results.
And this callback method is not blocked. At this point browser back to start another out-of-the-box processing.
This is well understood, because the time it takes to execute this method of DWR is unpredictable, if the call is blocked, and the server spends a considerable amount of time processing it. Then the browser will die here. From the perspective of the user experience is simply unacceptable.
The example code here is

...
Serverhandler.getstring ("Weiming", function (str) {//"weiming" is the parameter returned to the server
alert (str);
}); Serverhandler is the interface of the server method provided by DWR, see the DWR Web site for specific use.
Alert (1);
During execution, alert (1) is executed first and then alert (str) is executed after an unpredictable time.
If a simple call like Hello World is not going to go wrong.
But if the series of DWR function I want to perform is sequential, such as the result of the previous return, the simple sequence of code writing is not guaranteed to be executed.
var myID = null;
Serverhandler.getid (function (ID) {
MyID = ID; It's impossible to predict when this sentence will be executed.
});

Serverhandler.getuserwithid (MyID, function (name) {
/*
At this point MyID has no value, because the above MyID = ID This code is required for a period of time before the execution of
*/
Alert ("Hello:" + name);
});

For example, such a code would go wrong. So how to solve it?
The simplest way to implement this is to callback function nesting.
...
Serverhandler.getid (function (ID) {
Serverhandler.getuserwithid (ID, function (name) {
Alert ("Hello:" + name);
}
});
This allows us to guarantee the order of multiple Dwr method calls. This seems to solve the problem. But it's not perfect.
The reason is that when we put JavaScript and browser as an operational platform and a platform for logical business (AJAX applications, which are mentioned in the following JavaScript series), not a simple platform for presentation. This kind of callback function nesting is very difficult to control.
That's one of the ways I've started to point out the need to synchronize asynchronous calls.

Finally my solution in the company is this.
Write a semaphore class (JavaScript-oriented objects will be explained later), and when I need to execute a method, I apply a portion of the semaphore.
A queue in which the method needs to be executed is put into the semaphore queues to wait. Wait for the previous method (if present) to execute after execution.
The semaphore will be passed in as a parameter, so the method can decide whether to release the semaphore or continue distributing it.
Like what
var s = new semaphore ();
var myID = null;
S.P (function (e) {//Put method into semaphore queue
Serverhandler.getid (function (ID) {
MyID = ID;
S.V (); Release semaphore
}
});

S.P (function (e) {//The second method is placed in a semaphore queue, which is executed only after the preceding s.v () is executed.
Serverhandler.getname (MyID, function (name) {//At this point, you can guarantee that MyID must have a value
Alert ("Hello:" + name);
S.V ();
})
})

Here is a simple description of the method of signal volume.
Semaphores also support the creation of a semaphore, if the child semaphore is created, then the parent semaphore must wait for all children to return the semaphore before they can execute the code inside him.
Because the copyright of the code is the company's, so I am sorry, now can not give the corresponding complete signal volume implementation.
If I have time at the next end, I will give 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.