0

I call two functions in my js which get data via ajax:

getNumContentTotal(ctx);
getContentAll(ctx);

getNumContentTotal(ctx) sets a var that is required by getContentAll(ctx);

Is there a way of not executing the second function until my var is set?

panthro
  • 22,779
  • 66
  • 183
  • 324

2 Answers2

2

If you're using jQuery (which I'm assuming you are) then return the object that ajax call returns in your getNumContentTotal() and getContentAll() methods. jQuery returns a promise like object allowing you to manage callbacks in a serialized way:

EDIT: A better article on jQuery's promises: Understanding JQuery.Deferred and Promise.

function getNumContentTotal(ctx) {
  return $.ajax(...);
}

function getContentAll(ctx) {
  return $.ajax(...);
}

var promise = getNumContentTotal(ctx);
promise.pipe(function(data) {
  // do something with data
  return getContentAll(ctx);
}).done(function(data) {
  // do something with data
});
Sukima
  • 9,965
  • 3
  • 46
  • 60
1

What about something like this:

function getNumContentTotal(ctx)
{
    $.ajax({
        url: ajaxUrl,
        context: document.body
    }).done(function(data) {
        getContentAll(data);
    });

}

function getContentAll(ctx)
{
   //other function
}

So you only call the next function when the first function has been loaded. This way the variable you will give to the next function is always filled.

nkmol
  • 8,025
  • 3
  • 30
  • 51