问题
I am having issues with my php server (my computer is the only connection). I initially thought part of the reason was because of too many ajax requests (I have a script that executes an ajax request per keystroke) so I implemented a design to control the flow of ajax requests into a queue. Below is my code:
//global vars:
activeAjaxThread = 0; //var describing ajax thread state
ajaxQue = []; //array of ajax request objects in queue to be fired after the completion of the previous request
function queRequest(ajaxObj) {
ajaxQue.push(ajaxObj);
if (activeAjaxThread == 0) {
fireOffAjaxQue();
} else {
return 'ajax thread is running';
}
}
function fireOffAjaxQue () {
activeAjaxThread = 1;
//getLastRequest();
if ((ajaxQue.length > 0) && activeAjaxThread == 1) {
$.ajax(ajaxQue[0]).always( function () {
ajaxQue.shift();
if (ajaxQue.length > 0) {
fireOffAjaxQue(); //fire off another ajax request since this one has been completed.
}
});
}
activeAjaxThread = 0; //thread has finished executing
}
Implementation:
//create ajax object
var ajaxObj = {
url: 'someplace.php',
data: dataVar,
success: function (data) {...}
};
//send ajax object to que
queRequest(ajaxObj);
Then I found out that Javascript is multi-threaded and read a few articles on Javascript's event handling, such as this on http://ejohn.org/blog/how-javascript-timers-work/ by John Resig (jQuery extra-ordinaire)
That being the case, wouldn't the functions I've presented here produce no results since Javascript is already queuing my requests? The weird thing is that it appears to change it drastically. My server crashes less, (not that that deems it a solution in any stretch of the imagination... argh), and after it crashes and restarts, the previous queued ajax requests get sent, when earlier they seemed to all be sent at once and disappear into thin air on server crash.
If Javascript, being single-threaded, queues asychronous events:
- Is there any point to having an Ajax request manager, or a queue?
- Why does my code produce any results at all?
回答1:
Javascript is single threaded, but once the AJAX request is sent, it is out of javascript's hands, so to speak. That's the Asynchronous part of AJAX. The request is made and then the code moves on. Then when the response is received it is processed. Requests are not queued.
来源:https://stackoverflow.com/questions/14841718/if-javascript-is-not-multithreaded-is-there-any-reason-to-implement-asynchronou