我想在纯 JavaScript 或 Ajax 调用中一次进行 20 个服务调用。
有没有更好的办法?
你能帮我吗?
最佳答案
您可以使用 jQuery $.when()
函数同时发出多个 $.ajax()
请求。
它看起来像这样
$.when($.ajax(选项1), $.ajax(选项2))
.then(successFunc, failedFunc);
这是可行的,因为 $.ajax()
是一个与 Promise 兼容的对象,但如果有 20 个请求,它看起来会很糟糕。
您可以将 $.Deferred()
对象数组传递给 $.when()
函数,并执行您想要执行的操作。
它的工作原理如下
//Function to wrap the requests inside an array
function getRequests(){
var arrayOfDeferred = [];
//Wrap the below in a loop or something to get your 20 requests
//Push the ajax call to the array
arrayOfDeferred.push(
$.ajax({url: "...", success: function(result){
//maybe do something when the request is done?
}});
);
return arrayOfDeferred;
}
//Use it like this
var requests = getRequests();
$.when.apply(null, requests).done(function() {
console.log("All requests are made!");
});
当然,您必须调整代码才能正确获取请求,具体取决于它们之间的差异,但这应该让您了解如何完成它的基本概念。
查看 $.when()
的文档和$.deferred()
.
关于javascript - 我如何以 JavaScript Easy 方式一次性进行多次静态服务调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29407949/