Search code examples
javascriptasynchronousblocking

how to block execution until Asynchronous call is executed?


I am making an asynchronous call using plain java script whose result is to be used further. Here are the statements.

var x = function call();   //Asynchronous call
   alert(x);

here I am getting x as "undefined" .

then I tried to check the status of x using While loop as below

while(1){
  if(x != "undefined"){
       alert(x);
       break;
  }
}

Then the while condition is never getting a break. It goes on execution. Help me out to hoe to stop the execution until i receive result from Asynchronous call?


Solution

  • Asynchronous call returns the output once it processed. So your function should accept a callback which indeed runs when the function is executed.

    SO your code should look like this

    function asynccall (args...,  callback);
    
    function callback(data){
    alert(data); //Get the response and use it furher
    }