0

I have 2 cross domain jsonp requests that need to be completed before another method can be executed. So I tried the $.when() function

$.when(getX(), getY()).then(createXY);

getX() and getY() make $.ajax() requests to two different domains with separate jsonp callbacks.

Contrary to my original thought, createXY() gets invoked before the callbacks return. createXY() therefore does not have the data it needs.

Can someone please provide me an example on invoking a function when multiple async jsonp requests are completed?

E.A.
  • 321
  • 1
  • 4
  • 13
  • What do `getX()` and `getY()` return? They should return the value that `$.ajax()` returns. – Matt Ball Mar 27 '13 at 00:47
  • Avoid jQuery when it comes to promises [because](http://abdulapopoola.com/2014/12/12/the-differences-between-jquery-deferreds-and-the-promisesa-spec/) and [because](http://stackoverflow.com/questions/23951745/is-any-jquery-version-compliant-to-promise-a-specifications). Better use a promise polyfill like [lie](https://github.com/calvinmetcalf/lie) or [es6-promise](https://github.com/jakearchibald/es6-promise). – jaydoubleyou May 21 '15 at 07:45

2 Answers2

0

For $.when() to work, it must be passed a deferred object that it is waiting for. Make sure that your getX() and getY() functions are returning the deferred object created by the jQuery ajax call that each makes.

If you want help doing that, then post the code for getX() and getY().

Here's an example right from the jQuery doc for $.when():

$.when($.ajax("/page1.php"), $.ajax("/page2.php")).done(function(a1,  a2){
  /* a1 and a2 are arguments resolved for the
      page1 and page2 ajax requests, respectively */
  var jqXHR = a1[2]; /* arguments are [ "success", statusText, jqXHR ] */
  if ( /Whip It/.test(jqXHR.responseText) ) {
    alert("First page has 'Whip It' somewhere.");
  }
});
jfriend00
  • 683,504
  • 96
  • 985
  • 979
0

very silly mistake in the code. getX() and getY() called $.ajax() but never returns it. wrap the $.ajax() calls with return and the code is working fine now. Thanks for all your help!

E.A.
  • 321
  • 1
  • 4
  • 13