突发控制多个ajax请求 [英] Burst control over multiple ajax requests
本文介绍了突发控制多个ajax请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个 $。获取
的请求列表我使用
I have a list of $.get
requests that I handle using
$.when(...requests).then((...responses)=>{})
问题是API Im调用的突发速率,因此立即发送所有请求将使其中一小部分失败。
The problem is theres a burst rate on the API Im calling, so sending all the requests at once will make a fraction of them to fail.
是否有一种简单的方法可以使这些请求不立即使用jquery发送?
Is there a simple way of making these requests not to send immediatly using jquery?
推荐答案
$。得到应该返回Promise接口所以你可以像这个例子一样链接它们:
$.get should return also Promise interface so you can chain them like this example:
var urls = ["url1", "url2", "url3"];
var responses = [];
/*---- vanilla js example for use in snippet ------- */
function fakeGet(url) {
return new Promise(resolve => setTimeout(resolve, 1000, url + ' response'));
}
urls.reduce((chain, url) => {
return chain.then(res => {
res? responses.push(res) : '';
console.log('getting: ' + url);
return fakeGet(url);
});
}, Promise.resolve()).then(res => {
responses.push(res);
console.log('Complete!\n' + responses.join("\n"));
});
/* --------------- end of vanilla snippet ---------------*/
/* ------- using jQuery $.get --------------------
urls.reduce((chain, url) => {
return chain.then(res => {
res? responses.push(res) : '';
return $.get(url);
});
}, $.when()).then(res => {
responses.push(res);
console.log('Complete!\n' + responses.join("\n"));
});
---------------------------------------- */
这篇关于突发控制多个ajax请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文