延迟、ajax和排队功能

Deferred and ajax and queuing functionality

本文关键字:排队 功能 ajax 延迟      更新时间:2023-09-26

我正在实现一个各种信息的队列系统。当它达到一定数量时,我发送一个ajax请求....用户输入数据,当它到达某个点时,我发送它。但是,用户仍然可以输入数据。我不想失去这个…所以,我在想我可以使用$.Deferred/promise,同时将数据存储到某一点。触发ajax,并且只在先前延迟的请求成功时才允许新的请求…此外,如果输入的数据增加到我必须再次发送的程度,我会请求它。

我很难把我的大脑集中在如何实现的方法上。

===>捕获数据

=======>输入'n'数据量

=============> 将数据移动到"准备好了"桶。(任意的,让用户输入10个输入字段,然后存储到数组中。当array达到10时…

=============>使用10个条目启动ajax

在此期间,用户仍然可以输入数据。我想确保我仍然捕获它并保持队列和发送在10

我在考虑一个延迟的排队系统。不知道我是不是想多了

由于$.ajax()返回的jqXHR对象是Promise,因此可以使用。

var data = {
    // captured data goes here
};
function sendData( val ){
    // jqXHR object (which contains a promise)
    return $.ajax('/foo/', {
        data: { value: val },
        dataType: 'json',
        success: function( resp ){
            // do whatever needed
        }
    });
}
function when(){
    $.when(sendData(data)).done(function (resp) {
        when();
    });
}
when(); // use this within the if switch

假设您的队列是数组dataQueue,那么您可以这样做:

var dataQueue = [];//sacrificial queue of items to be sent in batches via AJAX request
var batchSize = 10;
var requesting = false;//flag used to suppress further requests while a request is still being serviced
//addToQueue: a function called whenever an item is to be added to he queue.
function addToQueue(item) {
    dataQueue.push(item);
    send();//(conditional on queue length and no request currently being serviced)
}
function send() {
    if(dataQueue.length >= batchSize && !requesting) {//is the queue long enough for a batch to be sent, and is no ajax request being serviced
        $.ajax({
            url: '/path/to/server/side/script',
            data: JSON.stringify(dataQueue.splice(0, batchSize)),//.splice removes items from the queue (fifo)
            ... //further ajax options
        }).done(handleResponse).fail(handleFailure).always(resetSend);
        requesting = true;
    }
}
function handleResponse(data, textStatus, jqXHR) {
    //handle the server's response data here
}
function handleFailure(jqXHR, textStatus, errorThrown) {
    //handle failure here
}
function resetSend() {
    requesting = false;//Lower the flag, to allow another batch to go whenever the queue is long enough.
    send();//Call send again here in case the queue is already long enough for another batch.
}

指出:

    没有特别的理由从send返回jqXHR(或其他任何东西),但如果您的应用程序将受益,请务必这样做。
  • resetSend不一定需要作为.always处理程序调用。从.done处理程序(而不是.error处理程序)调用将具有"失败时死亡"的效果。
  • 为了尽量减少名称空间(全局或其他)中的成员数量,您可以选择将整个内容封装在构造函数或单例名称空间模式中,这两种模式都非常简单。
  • 封装在构造函数中,将允许您拥有两个或多个具有所需行为的队列,每个队列都有自己的设置。
  • 这个演示有几行额外的代码来使进程可观察。
  • 在演示中,您可以将batchsize设置为15,add-add-add将队列长度设置为12,然后将batchsize减小为5并添加另一个项目。您应该看到两个连续的请求,队列中有3个剩余项。