user1672065
user1672065

Reputation: 33

Return deferred after another AJAX call

My question is relatively straight forward.

I have an array of deferreds waiting to be returned, the code is like this:

var deferreds = [];
for(var i = 0; i < 5; i==){
    deferreds.push(getOneResult(params));
}

var deferreds = [];
for(var i = 0; i < 5; i==){
    deferreds.push(getOneResult(params));
}

The "getOneResult" function looks like this:

function getOneResult(params){
  return $.ajax({
    url: myURL,
    data: params
  });
}

It worked fine until one day I decided to let the "getOneResult" function to execute another ajax process and then using the result from this ajax process to get the result, so now my problematic code looks like this:

function getOneResult(params){
  $.ajax({
    url: myOtherURL,
    data: params,

    success: function(){
      var result = arguments;
      return $.ajax({
        url: myURL,
        data: arguments
      });
    }

  });
}

Then all of a sudden all the items in "deferreds" array become "undefined". I am sure what I am doing sounds not right but is there anyway for me to run an ajax process before returning the deferred?

Upvotes: 1

Views: 73

Answers (1)

Evil Buck
Evil Buck

Reputation: 1068

try returning the second promise. The original promise will now use the wrapped, second ajax promise.

function getOneResult(params){
  return $.ajax({
    url: myOtherURL,
    data: params
  }).then(function() {
    return $.ajax({
      url: myURL,
      data: arguments
    });
  });
}

Upvotes: 3

Related Questions