0

I have this functions

function C(Id)
{
    var A=Y(Id);
    alert("A"+A);    
}

function Y(idImagen)
{
    var HR= new XMLHttpRequest();       
    HR.open("Post",DownloadImg_Php,true);
    HR.setRequestHeader("Content-type","application/x-www-form-urlencoded");                            
    HR.onreadystatechange=function()
    {       
        if(HR.readyState==4 && HR.status==200)
        {   
            return HR.responseText;
        }
    }
    //Ejecuta el Objeto                             
    HR.send(Variables); 
}

So here is my problem, the alert prints undifined and im pretty sure it is because the line runs befor XMLObject finish de request which is supose tu return and asign the expected value to the variable A.

So my question is, how can stop the code from running until value from Y is returned.

Cœur
  • 37,241
  • 25
  • 195
  • 267
  • 1
    you can't return from a callback. move your alert() call to the onreadystatechange() function – dandavis Dec 10 '14 at 02:12
  • there is one way to achieve functionality as you desire use `Promises` here is a example https://github.com/mdn/promises-test/blob/gh-pages/index.html – Mudaser Ali Dec 10 '14 at 02:27

1 Answers1

1

Actually you can use any library like jQuery or Angular with $http for making an XHR requests. It's more convenient and give us flexibility. If you don't want to, you can use Promises, it's on EcmaScript 6 CMIIW, you can use the shim from whenjs. It's for avoiding callbacks spaghetti in the future.

But if you want to use plain Javascript code, your alert must be inside

HR.onreadystatechange=function()
  {       
    if(HR.readyState==4 && HR.status==200)
    {
      alert("A"+HR.responseText);
    }
  }

Because it's asynchronous.

Andi N. Dirgantara
  • 2,050
  • 13
  • 20