Let’s remind you that JavaScript is single-threaded
A synchronous IO call BLOCKS THE ENTIRE THREAD
A simple fix is to use asynchronous style programming using callbacks.
Customer = Class.create({
initialize: function(customerId, cb) {
new Ajax.Request('some-url', {
method: 'get',
parameters: {
customerId: customerId
},
onSuccess: (function() {
this.setCustomerInfo.apply(this, arguments);
cb.apply(this, arguments);
}).bind(this)
}
},
setCustomerInfo: function(response) {
//for the sake of this example I will leave out the JSON validation
this.customerInfo = response.responseText.evalJSON();
}
});
var c = new Customer(1, function() {
document.write(customer.customerInfo.firstName);
});