2017-07-27 180 views
0

是否有任何方便的方法来制作XMLHTTP请求Javascript?例如发送前等待3秒钟?我有一个数组的全名XMLHTTP请求的延迟

var items = [ 
    { url: "www.google.com/getChocolate", name: "Chocholate"}, 
    { url: "www.google.com/getCake", name: "Cake"}, 
    { url: "www.google.com/getCookie", name: "Cookie"}, 
]; 

for (var i = 0; i < items.length; i++) { 
    var xhr = new XMLHttpRequest(); 
    xhr.onreadystatechange = function() { 
     if (this.readyState == 4 && this.status == 200) { 
      var data; 
      data = JSON.parse(xhr.responseText); 
      // processing data here 
     } 
    }; 
    xhr.open("GET", items[i].url, false); 
    xhr.send(); 
    // I somehow have to force to send the request for each item only every 3 seconds 
} 

并为他们每个人我想接收来自服务器的JSON响应,但它禁止我的某个时候,如果我过于频繁发送请求,所以我需要给他们像每3秒,等待响应,处理响应并开始新的响应。 我想我必须使它同步,所以我已经在xhr.open中存在错误的参数。

+0

'setTimeout'就是你要找的东西。 –

+0

*“我必须让它同步”* ......永远不要这么做!它阻止了整个用户界面,因为这是一个糟糕的做法而被弃用 – charlietfl

+0

如果我在循环中为请求添加'setTimeout',它会等待给定的时间并一次发送所有项目的请求,我需要它们发送一个一。 –

回答

0

H I朋友,

我刚才看到您的帖子,我知道你想要做一个请求队列 - 在3秒后发出的第一个请求,并等待它完成,然后发送下一个和下一个,直到结束队列。

我做了一个非常简单的类RequestRequestManager这将为你做这个。

看看代码,让我知道如果有什么不清楚给你。尝试阅读评论。

var items = [{ 
 
    url: "www.google.com/getChocolate", 
 
    name: "Chocholate" 
 
    }, 
 
    { 
 
    url: "http://en.wikipedia.org/w/api.php?action=opensearch&format=json&limit=15&origin=*&search=cake", 
 
    name: "Cake" 
 
    }, 
 
    { 
 
    url: "http://en.wikipedia.org/w/api.php?action=opensearch&format=json&limit=15&origin=*&search=cookie", 
 
    name: "Cookie" 
 
    }, 
 
]; 
 

 
/* First prepare array of requests that later will be send */ 
 
var requests = []; 
 
for (var i = 0; i < items.length; i++) { 
 
    requests.push(new Request(items[i].url)); 
 
} 
 

 
/* Initialize the object that will be responsible for 
 
* request sending and process the requests */ 
 
var manager = new RequestManager(requests); 
 
manager.process(); 
 
manager.onSend(function(url, response) { 
 
    /* this code will fire once a request is completed, no matter if success of failed */ 
 
    console.log('request to ' + url + ' completed ....'); 
 
    console.log('----------------------------------------'); 
 
}) 
 

 

 
/** 
 
* This class is a wrapper that will hold the request 
 
* and will be responsible to send it with a delay of 3 seconds 
 
* 
 
* @param {string} url - this is the url which is going to be requested 
 
* @returns {Request} - new Request object 
 
*/ 
 
function Request(url) { 
 
    var that = this, resolve, reject; 
 
    that.url = url; 
 

 
    that.promise = new Promise((res, rej) => { 
 
    resolve = res; 
 
    reject = rej; 
 
    }); 
 

 
    that.xhr = new XMLHttpRequest(); 
 
    that.xhr.onreadystatechange = function() { 
 
    if (that.xhr.readyState == 4) { 
 
     if (that.xhr.status == 200) { 
 
     var data = null; 
 
     try { 
 
      data = JSON.parse(that.xhr.responseText); 
 
      resolve(data); 
 
     } catch (e) { 
 
      reject(e); 
 
     } 
 
     } else { 
 
     reject({ 
 
      statusText: that.xhr.statusText, 
 
      response: that.xhr.response 
 
     }); 
 
     } 
 
    } 
 
    }; 
 

 
    that.send = function() { 
 
    /* send request after 3 seconds */ 
 
    setTimeout(function() { 
 
     that.xhr.open("GET", that.url, true); 
 
     that.xhr.send(); 
 
    }, 3000) 
 

 
    return this; 
 
    } 
 
} 
 

 

 
/** 
 
* This class is responsible for processing all the request 
 
* The main role is to call the Request's send method, 
 
* wait the request to complete and then call the next request from the queue 
 
* until all the requests are processed 
 
* 
 
* @param {Array} requests - this is an array of Request objects 
 
* @returns {RequestManager} new RequestManager object 
 
*/ 
 
function RequestManager(requests) { 
 
    var that = this, 
 
    callback; 
 
    that.requests = requests; 
 

 
    that.onSend = function(cb) { 
 
    callback = cb; 
 
    } 
 

 
    that.process = function() { 
 
    console.log('Starting requests sending .......'); 
 
    doRequestRecursive(that.requests.pop()); 
 
    } 
 

 
    function doRequestRecursive(request) { 
 
    request.send().promise.then(function(data) { 
 
     console.log('request ' + request.url + ' success ...'); 
 
     callback(request.url, data); 
 
    }, function(err) { 
 
     console.log('request ' + request.url + ' failed ...'); 
 
     callback(request.url, err); 
 
    }).then(function() { 
 
     var nextRequest = that.requests.pop(); 
 
     if (nextRequest) { 
 
     doRequestRecursive(nextRequest); 
 
     } 
 
    }); 
 
    } 
 
}

样本代码片段将请求发送到维基百科以证明他们是成功的,因为你的链接不工作的。