1

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;
}

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.