-2

I have two functions that I want to load them one by one. They are like this:

<script>
    //first function
    load_ajax_select(id);
    //second fucntion
    fadeIn_that_div();
</script>

I want to know how the second function can be done after the first one has loaded.

Thanks.

Majid Sadr
  • 11
  • 3

1 Answers1

1

Let's assume that load_ajax_select looks something like this:

function load_ajax_select() {
    $.get("/some/url", function(stuff) {
        $("some selector").html(stuff);
    });
}

or

function load_ajax_select() {
    $("some selector").load("/some/url");
}

or similar, probably with some other logic. In order for it to make it possible for other things to get notification when it's done, the most flexible thing it can do is return a promise. Depending on what it does, it may be simplest to return the promise it already has from the $.get:

function load_ajax_select() {
    return $.get("/some/url", function(stuff) {
        $("some selector").html(stuff);
    });
}

...or sometimes it's useful to create your own:

function load_ajax_select() {
    var d = $.Deferred();
    $("some selector").load("/some/url", function() {
        d.resolve();
    });
    return d.promise();
}

...although normally if you have one already, creating your own is an anti-pattern.

Code that doesn't care about knowing when the result occurs can just ignore the return value. But your code that needs to know can use it:

load_ajax_select().then(fadeIn_that_div);

or sometimes you may need

load_ajax_select().then(function() { fadeIn_that_div(); });

...if for some reason you can't call fadeIn_that_div directly via then.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875