1

I have the following code.

var foo = {
    ajaxcall : function(){
       var _obj = {};
       $.ajax({
            headers: {
                'Content-Type': "application/json; charset=utf-8",
                'dataType': "json"
            },
            async: false,
            url: "/getservertime"
        }).done(function(resp,stat) {
            resp = JSON.parse(resp);
            _obj.resp = resp;
            console.log(_obj);
            return _obj;
        });
    },
    init: function(){
        this.somefunction(this.ajaxcall());
    },
    somefunction: function(_data){
        console.log(_data); // coming as undefined
    }
}
foo.init();

How can I wait for execution of ajax to complete and then execute somefunction method. I have already tried async: false. Looks like some other issue.

the
  • 21,007
  • 11
  • 68
  • 101
ghost...
  • 975
  • 3
  • 16
  • 33

2 Answers2

4

How can I wait for execution of ajax to complete and then execute somefunction method.

You can't, without using async: false, and that's a bad idea.

Instead, you use a callback (either directly, or via promises). Here's a minimal modifications example:

var foo = {
    ajaxcall : function(callback){       // <== Accept callback
       var _obj = {};
       $.ajax({
            headers: {
                'Content-Type': "application/json; charset=utf-8",
                'dataType': "json"
            },
            async: false,
            url: "/getservertime"
        }).done(function(resp,stat) {
            resp = JSON.parse(resp);
            _obj.resp = resp;
            console.log(_obj);
            callback(_obj);               // <== Call it
        });
    },
    init: function(){
        this.ajaxcall(this.someFunction.bind(this)); // <=== Pass it
    },
    somefunction: function(_data){
        console.log(_data); // coming as undefined
    }
}
foo.init();

Note the this.someFunction.bind(this) bit: That creates a new function that, when called, will call someFunction with the correct this value. Now, your someFunction as written doesn't actually care about this, but I assume in your real code it would.

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

You'll need to call it within the done() handler. Something like:

var foo = {
    ajaxcall : function(callback){
       var _obj = {};
       $.ajax({
            headers: {
                'Content-Type': "application/json; charset=utf-8",
                'dataType': "json"
            },
            async: false,
            url: "/getservertime"
        }).done(function(resp,stat) {
            resp = JSON.parse(resp);
            _obj.resp = resp;
            console.log(_obj);

            callback(_obj);
        });
    },
    init: function(){
        this.ajaxcall(this.somefunction);
    },
    somefunction: function(_data){
        console.log(_data); // coming as undefined
    }
}
foo.init();
Paul Roub
  • 36,322
  • 27
  • 84
  • 93