0
$(document).ready(function () {
    $("#anca").click(function (e) {
        viewModel.CurrentVisit.GetById(StartValidation);
        //Below statement executes before startValidation callback function //is executed
        var x= true;
    });
});

As, you can see here I am calling the function GetById and StartValidation is the callback function

self.GetById = function (SuccessCallback) {
        var UId= self.Id();
        UId = UId.replace('emp/', '');
        $.ajax({
            type: "GET",
            url: "/api/v1/emp/" + UId,

            traditional: true,
            success: function (data) {                
                SuccessCallback(UserId);
            },
            error: function (data) {
                debugger;
            }
        });
    }

The callbackfunction is defined as such

function StartValidation(UserId) {
    if (viewModel.CurrentUser.Id() != UserId) {
        alert('Fail');
        return false;
    }
}

Basically the callback function executes later and the statement var x= true; executes first. i understand its anasync call so how do I wait for callback function to complete beore the statement var x= true; is executed ?

user1005310
  • 737
  • 2
  • 12
  • 40
  • 1
    It doesn't look like your callback would be called at all. – radiaph Mar 19 '15 at 19:44
  • Could you not move var x = true; into the callback? – Matt Johnson Mar 19 '15 at 19:48
  • 1
    You don't "wait" -- it's asynchronous". You need to do whatever is depending on the callback either in the callback itself, or make the callback call yet another function when it finishes. In you example, either move the "var x = true" to the callback itself, or move it to a separate function and make the callback call that function when it finishes. – Matt Runion Mar 19 '15 at 19:49
  • @user1005310, I actually hadn't noticed the naming issue. I meant that your GetById function does not call the callback, nor pass it to anyone else to be called. – radiaph Mar 19 '15 at 19:49

0 Answers0