0

I'm not sure I follow exactly how deferred, promises and $.when() work. I've read through https://api.jquery.com/jquery.when/, but I'm curious about whether a function with an ajax call can be used inside of $.when().

I see this example on the documentation:

$.when( $.ajax( "test.aspx" ) ).then(function( data, textStatus, jqXHR ) {
  alert( jqXHR.status ); // Alerts 200
});

Is this also an acceptable method?

$.when( $.ajax( anotherFunction() ) ).done(
//on completion of the ajax call inside "anotherFunction()" do something here.
);

anotherFunction(){$.ajax...do some ajax stuff here.}

The specific case I'm looking at is loading a list of available dashboard, then once the list is populated on the front end, capture a specific dashboard out of the list and run a load function for it.

I'm finding that it does not break and will run (maybe?) but I don't know if it's the proper way to code it out or if it's just not working and not breaking at the same time.

Thanks for any advice and expertise on this!

-Jeff

Juan Serrats
  • 1,358
  • 5
  • 24
  • 30
onx2
  • 76
  • 8
  • `$.when` is rendandant for making a single ajax call ... just make second in callback of first one when the needed data is available – charlietfl May 14 '17 at 15:05

1 Answers1

0

[...] if a function with an ajax call can be used inside of $.when().

Your example would work if you skip the surrounding $.ajax and the function itself returns the $.ajax-call. If what you're passing to $.when is not a Deferred (in your case, the function returns undefined), it will resolve immediately, what I think is not what you want. Additionally, $.when is pointless when you only have a single Deferred. If your function will return the $.ajax, you can just do something like anotherFunction().done(...).

The specific case I'm looking at is loading a list of available dashboard, then once the list is populated on the front end

Indeed, that's the idea behind $.when: Waiting for multiple Deferred to finish. You may just pass them as parameters, e.g.

let d1 = $.ajax(...);
let d2 = $.ajax(...);

$.when(d1, d2).done(...)

But if you just have one ajax call, you won't need $.when.

SVSchmidt
  • 6,269
  • 2
  • 26
  • 37