AJAX Promises using Array

前端 未结 1 1652
不思量自难忘°
不思量自难忘° 2020-11-28 16:32

I\'m trying to make several AJAX calls (let\'s say 2) using promises. Basically I want to be able to merge the two responses together, perform some analysis on them as a wh

相关标签:
1条回答
  • 2020-11-28 16:54

    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?

    Not on arrays, yes. You can call this method only on Promise and Deferred objects, like the one produced by $.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.

    As stated in the docs for $.when, it resolves the result promise with multiple arguments - and when the input promises themselves did yield multiple values (such as $.ajax does), each argument is an arguments object of the respective promise resolution. You were only getting the first of them with response, but there are responseArray.length (letsSayTwo) arguments to the callback.

    How should I go about getting the correct responses from both AJAX calls?

    You want to extract the first item (response data) from each arguments object, so you can use 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);
    });
    
    0 讨论(0)
提交回复
热议问题