panthro
panthro

Reputation: 24059

Calling a function and not moving on until complete?

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?

Upvotes: 0

Views: 91

Answers (2)

Sukima
Sukima

Reputation: 10084

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
});

Upvotes: 2

nkmol
nkmol

Reputation: 8091

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.

Upvotes: 1

Related Questions