Reputation: 4503
I have the following code on my webpage:
<script type="text/javascript">
debugger; // 1
var dataClassObj = new DataClassList();
dataClassObj.init();
var viewModel = dataClassObj.getModel();
debugger; // 2
</script>
in a js file I have:
var DataClassList = function () {
};
DataClassList.prototype = function () {
var viewModel;
// private memebers
var init = function () {
var self = this;
$.ajax({
url: "xxx",
type: 'GET',
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data) {
// code
});
// code
self.viewModel = viewModel;
ko.applyBindings(viewModel);
debugger; // 3
},
error: function(xhr, status, error) {
$('#lblError').show();
}
});
},
getModel = function () {
debugger; // 4
return viewModel;
};
// public members
return {
init: init,
getModel: getModel
};
}();
When I run this using Chrome's developer tool, hitting the debugger points. I thought it would run in 1->3->4->2, but it seeme always hit the debugger statements in this order 1->4->2->3 i'm confused as to why it does that, I thought Javascript was synchronous so it would hit 1 and then make the call to init which would trigger 3 and then call 4 and finally 2.
Upvotes: 0
Views: 46
Reputation: 3590
JavaScript is syncronous with the exception of ajax calls, setTimeout() and setInterval().
Upvotes: 0
Reputation: 3826
$.ajax is asynchronous. It will do that call after the other code has run (usually).
Upvotes: 2