0

I has an array of ajax requests:

let requests = urls.map(function(url){
    return $.ajax({url: url, dataType: 'json'});
});

and I want to process them on. I am using when:

$.when(...requests).then(function(...responses){
    let processed = responses.map(function(responseRaw, index){
        let response = responseRaw[0];
        return /*some processed request*/;
    });
    //do something else
}).fail(function(error){
   //process errors
});

jquery returns responseRaw: it is array-like object containing data, status and something else. This works fine with several requests, but fails with one request: instead of one argument function then expects a three argument function (responseRaw spreaded). This is not a spread operator problem, but jquery one.

How to avoid that? My workaround:

$.when(...requests).then(function(){
    let responses;
    if (arguments.length == 3 && arguments[1] == "success"){
        responses = [arguments];
    } else {
        responses = Array.from(arguments);
    }

(BTW, is there a more clean way to get data instead of responseRaw[0]?)

ov7a
  • 1,497
  • 4
  • 15
  • 34
  • Not entirely sure, but does this has to do anything with the ... operator? I mean, it should be an array, but when you have only one request, this might end with different arguments (as it turns out). Am I correct, or my assumption is absolutely wrong? – logout Mar 19 '18 at 11:58
  • as I've already written, this is unlikely related to spread operator problem. I've checked `arguments` and their size is equal to 3. `requests` is always an array, so the problem should not be related to it. – ov7a Mar 19 '18 at 12:48

1 Answers1

0

In .When() and .done() using an array with .done the same problem is described. Seems like there is no better solution to this: according to JQuery documentation

If a single Deferred is passed to jQuery.when(), its Promise object (a subset of the Deferred methods) is returned by the method.

ov7a
  • 1,497
  • 4
  • 15
  • 34