asynchronous and wait for response in JavaScript

Asynchronous programming is a technique that enables your program to wait some other events and tasks. by default JavaScript does not wait for responses of other functions, events and actions.

There are following ways that can help you made JavaScript code Async like to wait for a event to perform an action.

Callback functions:

Callback functions helps JavaScript to perform Async actions. Like when you need to update DOM and you want to get content  from your server you will send a HTTP request to your server to get your desired content. In this case JavaScript will not wait HTTP request response  which results may be an error or null response 

So you to handle it with your logic there are followings ways  that can help you perform this action.

function someCallBackfun(someAction,res){

var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      
     someAction(xhttp.responseText);
    }
};
xhttp.open("GET", "filename.php?" + res, true);
xhttp.send();

}
function displayUserName(value) {
 document.getElementById("userName").innerHTML = value;
}

var getResponseFromserver = someCallBackfun(displayUserName,'name');

function displayUserRollNumber(value) {
 document.getElementById("rolenumber").innerHTML = value;
}

someCallBackfun(displayUserRollNumber,'rolenumber');

JavaScript Promises:

A Promise is a proxy for a value not necessarily known when the promise is created. It allows you to associate handlers with an asynchronous action's eventual success value or failure reason. The following is a comprehensive example of promise to wait for a response and perform action once some response is came from server.

let somePromise = new Promise(function(resolve, reject) {

	var xhttp = new XMLHttpRequest();
	xhttp.onreadystatechange = function() {
	    if (this.readyState == 4 && this.status == 200) {
	     	
	    	resolve(xhttp.responseText); // when successful

	    }
	};
	xhttp.open("GET", "filename.php?" + res, true);
	xhttp.send();

});

somePromise.then(function(value) { 

	document.getElementById("rolenumber").innerHTML = value;
 });

async function:

The keyword async before a function force the function to return a value.

NOTE: the await keyword can only be used inside an async function.

function someasyncfun() {
	var xhttp = new XMLHttpRequest();
	xhttp.onreadystatechange = function() {
	    if (this.readyState == 4 && this.status == 200) {
	     	
	    	resolve(xhttp.responseText); // when successful

	    }
	};
	xhttp.open("GET", "filename.php?" + res, true);
	xhttp.send();

	return xhttp;
}

async function asyncCall() {
  const result = await someasyncfun();
  console.log(result);
  // some output once HTTP request responsed back
}

Tags:

Share:

Related posts