Reputation: 367
From another method I am calling the method below, the problem is its always returning 0 while data[4] is not 0. If javascript is single threaded how come there is a synchronization problem here? if not can you please explain and suggest a fix.
function GetVMData(url_s){
var cpu_USG = 0;
$.ajax({
url: url_s,
crossDomain: true,
dataType: 'jsonp',
success: function(data) {
cpu_USG = data[4];
},
error: function(xhr, status, error) {
alert('failed')
}
});
return cpu_USG;
}
Upvotes: 1
Views: 51
Reputation: 254916
You may use jquery deferreds:
// the function definition
function GetVMData(url_s){
return $.ajax({
url: url_s,
crossDomain: true,
dataType: 'jsonp',
error: function(xhr, status, error) {
alert('failed')
}
}).pipe(function(data) { return data[4]; });
}
// function call example
GetVMData('some url').done(function(cpu_USG) {
alert(cpu_USG);
});
This solution is MUCH better than making ajax request synchronous.
Upvotes: 2