smtp
smtp

Reputation: 159

call a function after another function is completed

I am trying to call another function after load() is completed. I first tried to check with alert(), however, I see the alert before load() is done. I am able to successfully load content in load() function. However, alert() is empty.

$(document).ready(function(){   

    load();
    $.when(load()).done(function(){
        alert((document.getElementById('item').innerHTML));
    });        

    function load()
    { 
        $("#item").load("/somepage.aspx", function (response, status, xhr){
              if ( status == "error" ) {
                var msg = "error: ";
                $( "#error" ).html( msg + xhr.status + " " + xhr.statusText );
              }
        });                         
    };
});

Upvotes: 2

Views: 17785

Answers (3)

Sagi
Sagi

Reputation: 9284

You can use the new Promises API which is already implemented in most major browsers.

var jsonPromise = new Promise(function(resolve, reject) {
    // do a thing, possibly async, then…

    if ( /* everything turned out fine */ ) {
        resolve("Stuff worked!");
    } 
    else {
        reject(Error("It broke"));
   }
});

jsonPromise.then(function(data) {
    console.log(result); // "Stuff worked!"
}, function(err) {
    console.log(err); // Error: "It broke"
});

Upvotes: 0

Barmar
Barmar

Reputation: 780984

You need load() to return a promise, and then you pass this promise to $.when.

.load() doesn't return a promise, it returns the jQuery collection that it was called on (for chaining purposes). You can rewrite load() using $.get() instead, which returns a jQXHR, which implements Deferred (that's jQuery's promise class).

var p = load();
$.when(p).done(function() {
    alert($("#item").html());
});

function load() {
    return $.get("/somepage.aspx", function (response, status, xhr){
        $("#item").html(response);
        if ( status == "error" ) {
            var msg = "error: ";
            $( "#error" ).html( msg + xhr.status + " " + xhr.statusText );
        }
    });
}

You don't actually need to use $.when, you can just write:

p.done(function() { ... });

Upvotes: 1

Nikhil Aggarwal
Nikhil Aggarwal

Reputation: 28455

You can use callback functions and update your code to following

$(document).ready(function(){   

    load(function(){
        alert((document.getElementById('item').innerHTML));
    });

    function load(callback)
    { 
        $("#item").load("/somepage.aspx", function (response, status, xhr){
              if ( status == "error" ) {
                var msg = "error: ";
                $( "#error" ).html( msg + xhr.status + " " + xhr.statusText );
              }
              if(callback) {
                   callback();
              }
        });                         
    };
});

Upvotes: 1

Related Questions