javascript - 使用数组的 AJAX Promise

标签 javascript jquery ajax promise

我正在尝试使用 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/

相关文章:

javascript - 为什么 ember serve 与 index.html 的行为不同?

javascript - 使用 "choose file"输入更改 div backgroundImage

javascript - jQuery 文档宽度与数学

即使为表单元素定义了 name 属性,JQuery form.serialize() 也会返回空字符串

javascript - React/Redux - 处理错误和错误代码

添加 Javascript 下拉菜单

jquery - 帮助 960 网格和 jquery

javascript - PHP - 为 Ajax Post 的表单数据附加新值

javascript - AJAX错误303处理

javascript - jquery图像替换?