【问题标题】:properly queuing different ajax requests正确排队不同的ajax请求
【发布时间】:2017-11-09 13:07:38
【问题描述】:

我看到了很多队列 ajax 请求的解决方案,但我试图了解如何针对这种情况实施一种解决方案。应该是推送和转移队列吗?:

var urlList = ['urlA', 'urlB', 'urlC', ...];

function initSession() {
    for (var i = 0; i < urlList.length; i++) {
        getResponse(urlList[i]); // this is what I would like to queue.
    }
}

function getResponse(theURL) {
    steps.shuffleLetters({
        "text": messages[mesInd]
    });
    $.ajax({
        method: 'GET',
        url: theURL,
        dataType: 'text',
        success: function(data) {
            setTimeout(function() {
                steps.shuffleLetters({
                    "text": data
                });
            }, 1000);
            mesInd = mesInd + 1;
        },
        error: function(data) {
            setTimeout(function() {
                steps.shuffleLetters({
                    "text": "Click Again!"
                });
            }, 1000);
            mesInd = 0;
        }
    });
}

【问题讨论】:

  • $.ajax 正在返回一个承诺。我认为这是要走的路。
  • @kevinSpaceyIsKeyserSöze 返回的对象的行为类似于Promise,但不是一个:"从 jQuery 1.5 开始,$.ajax() 返回的 jqXHR 对象实现了 Promise 接口,为它们提供了所有Promise 的属性、方法和行为"
  • @Andreas 感谢您的提示。有点吹毛求疵:)?

标签: javascript ajax queue


【解决方案1】:

您可以通过删除 for 循环并在当前请求成功后调用下一个 url 来做到这一点

检查下面的代码:

var urlList = ['urlA','urlB','urlC',...];
var length = urlList.length;
var currentRequest = 0;
getResponse(urlList[currentRequest]);


function getResponse(theURL){
 steps.shuffleLetters({"text": messages[mesInd]});
    $.ajax({
        method: 'GET',
        url: theURL,
        dataType: 'text',
        success: function (data) {
             setTimeout(function(){steps.shuffleLetters({"text": data});}, 1000);
             //Here you will call the next request 
             currentRequest +=1;
             if(currentRequest < length)
             {
                 getResponse(urlList[currentRequest]);
             }

             mesInd = mesInd+1;
        },
        error: function (data) {
            setTimeout(function(){steps.shuffleLetters({"text": "Click Again!"});}, 1000);
            mesInd = 0;
        }
    });
}

【讨论】:

  • 感谢 @Amr-Labib 发现它。我的错!即使这样,当请求一个接一个地发出时,我也无法获得排队响应
  • 队列响应是什么意思...上面的代码将保证每个请求在完成之前的请求之后被调用...
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-07
  • 2017-01-03
  • 2011-06-14
  • 1970-01-01
  • 2012-03-20
相关资源
最近更新 更多