运行 多个相似 ajax 调用的正确方法,具有相同的完成功能,输入数据不同

Proper way to run multiple similar ajax calls with same done function, differing in input data

所以我正在尝试向同一个地方发送多个 ajax 请求以获得几乎相同的 json,但我每次都会发送不同的数据。

这是我目前所拥有的,我将每个 ajax 请求添加到一个数组,然后尝试 运行 数组上的 $.when,但没有任何反应。我发誓我以前见过这个,这就像它是如何完成的。只是想知道 运行 多个 ajax 调用的正确方法是什么。它们彼此不依赖,但结果 json 被操纵并为每个请求使用相同的方式。

这是我的代码:

var requests=[]
$('.element').not('.w').each(function(){
        requests.push($.ajax({url:'https://api.url.com', data:{'q':$(this).children('.supportingText').text(), 'token':''}, dataType:'jsonp', method:'GET'}));
    });
$.when(requests).done(function(response){
    //check if element in response object is something and then add to array and edit the .element that is currently on.
}

您可以使用 Promise.all:

Promise.all(requests).then((responses) => {
  return responses.map((response) => {
    // check if element in response object is something and then add to array and edit the .element that is currently on.
  });
});

与真正的承诺不同,jQuery的承诺有点不同。 $.when 没有在它的参数中使用一个 promises 数组,它需要多个参数

使用 Function#apply 你可以使用数组来“填充”参数

类似地,.done 被调用时每个输入参数有一个参数

您的代码可以重写:

$.when.apply($, requests).done(function(){
    var response = [].slice.call(arguments);
    // response is an array of responses
})

或 ES2016+ 扩展运算符(如果您不这么认为,... 实际上是代码的一部分)

$.when(...requests).done(function(...response){
    // response is an array of responses
})