如果 Javascript 不是多线程的,是否有任何理由实现异步 Ajax Queuing?

2022-01-21 00:00:00 queue jquery javascript single-threaded

我的 php 服务器出现问题(我的计算机是唯一的连接).我最初认为部分原因是因为 ajax 请求太多(我有一个脚本,每次击键执行一个 ajax 请求),所以我实现了一个设计来控制 ajax 请求进入队列的流程.以下是我的代码:

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
}

实施:

//create ajax object
var ajaxObj = {
  url: 'someplace.php',
  data: dataVar,
  success: function (data) {...}
};
//send ajax object to que
queRequest(ajaxObj);

然后我发现 Javascript 是多线程的,并阅读了一些关于 Javascript 事件处理的文章,例如 http://ejohn.org/blog/how-javascript-timers-work/ 作者:John Resig(jQuery extra-ordinaire)

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)

既然如此,我在这里介绍的函数不会产生任何结果,因为 Javascript 已经在对我的请求进行排队了吗?奇怪的是,它似乎彻底改变了它.我的服务器崩溃更少,(任何想象力中的并不是认为它是一个解决方案...啊),并且在它崩溃并重新启动后,之前排队的 ajax请求被发送,而早些时候它们似乎都被同时发送并在服务器崩溃时消失在空气中.

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.

如果 Javascript 是单线程的,对异步事件进行排队:

If Javascript, being single-threaded, queues asychronous events:

  1. 拥有 Ajax 请求管理器或队列有什么意义?
  2. 为什么我的代码会产生任何结果?

推荐答案

Javascript是单线程的,但是一旦发送AJAX请求,就脱离了javascript的控制,可以这么说.这就是 AJAX 的异步部分.发出请求,然后代码继续.然后在收到响应时对其进行处理.请求没有排队.

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.

相关文章