我正在尝试使用 Promise 进行多个 AJAX 调用(比方说 2 个)。基本上我希望能够将两个响应合并在一起,对它们作为一个整体进行一些分析,然后吐出一个响应。 现在,我有:
var responseArray = [];
for (var i=0; i<letsSayTwo; i++) {
responseArray.push(someAjaxCall(data));
};
responseArray.done(function(response) {
var spit = someAnalysis(response);
console.log(spit);
});
responseArray.fail(function(response) {
console.log('fail');
});
就目前情况而言,我在控制台中收到“Uncaught TypeError: Object [object Array] has no method 'done'”错误。我认为我不能使用这种方法是正确的吗?我研究了使用( http://gregfranko.com/blog/jquery-best-practices/ )中的以下代码,但我似乎无法得到我需要的响应。
$.when.apply(this, responseArray).then(function(response) {
console.log(response);
});
相反,我得到的是 [response, "success", response],其中第一个响应是一个 AJAX 调用的正确返回响应,最后一个响应是实际的调用本身。我应该如何从两个 AJAX 调用中获得正确的响应?
我希望这一切都有道理。谢谢!
最佳答案
As it stands, I'm getting an
Uncaught TypeError: Object [object Array] has no method 'done'
error in console. Am I correct in thinking that I can't use this method?
不是在数组上,是的。您只能在 Promise 和 Deferred 对象上调用此方法,例如 $.when.apply(this, responseArray)
… but I can't seem to get the response that I need. Instead, what I get is
[response, "success", response]
where the first response is the correct return response for one of the AJAX calls and the last response is the actual call itself.
如 docs for $.when
中所述,它用多个参数解析结果 promise - 当输入 promise 本身确实产生多个值时(例如$.ajax
),每个参数都是一个参数对象各自的 promise 决议。您仅通过 response
获得其中的第一个,但回调中有 responseArray.length
(letsSayTwo
) 参数。
How should I go about getting the correct responses from both AJAX calls?
您想要从每个 arguments
中提取第一项(响应数据)对象,因此您可以使用 map
:
$.when.apply(this, responseArray).done(function() {
var responses = $.map(arguments, function(args) { return args[0]; }),
spit = someAnalysis(responses);
console.log(spit);
}).fail(function(jqXHR, textStatus, errorThrown) {
console.log('fail: '+textStatus);
});
关于javascript - 使用数组的 AJAX Promise,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19088981/