Asynchronous code not working

for (var i = 0; i < 100; i++) {
	var request = new XMLHttpRequest();
	request.open('GET', 'data.txt', false);
	request.send();
	if (request.status===200) {
		console.log(request);
		document.writeln(request.responseText);
	}	
}

the above code whose live version is here on the server is actually synchronous.

But when I convert this to asynchronous:

request.open('GET', 'data.txt', true);

Expected result →
In the real-time hello world would print in the browser w/o waiting for all the 100 requests to be processed.

But that is not happening.

Hi @codeispoetry, this is because the scope of var declarations is not limited to regular blocks (such as inside a for loop) but only to functions; so effectively your’re reassigning the same request variable with a new XHR in each loop. To avoid this, either use const instead of var as this is truly block-scoped, or wrap the request initialization in a function (which would be much nicer anyway IMHO):

function sendRequest () {
  var request = new XMLHttpRequest()
  
  request.open('GET', 'data.txt')
  request.send()

  if (request.status === 200) {
    console.log(request)
    document.writeln(request.responseText)
  }
}

for (var i = 0; i < 100; i++) {
  sendRequest()
}
1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.