1

In the following js snippet

request = new XMLHttpRequest
request.open('GET', '/my/url', true)
request.send()

request.onload = function() {
  data = JSON.parse(this.response)
}

should the assignment of the on load be before the send() to avoid a race condition. Or does the browser deal with it for you (by firing the on load when you get round to assigning it).

Daniel James Bryars
  • 4,429
  • 3
  • 39
  • 57
  • 1
    JavaScript is fundamentally single-threaded, so no, there's no race condition. – p.s.w.g Jan 31 '14 at 00:57
  • 1
    @PatrickEvans I'm pretty sure the browser won't initiate the request until after the browser's thread is free. But I'm not sure if that's specified behavior. I suppose it's possible some browsers may implement this differently. – p.s.w.g Jan 31 '14 at 01:03
  • 1
    It's at least considered good practice to place the event handlers before the `open()` and `send()` calls to make it sure it's not an issue, even if the chances are slim for a race condition, it's so easy to make sure you avoid it. – adeneo Jan 31 '14 at 01:09
  • You shouldn't use onload. Use `onreadystatechange`, testing for `request.readyState == 4 && request.status == 200`. – StackSlave Jan 31 '14 at 01:11

1 Answers1

1

Your request should look more like:

var request = new XMLHttpRequest || new ActiveXObject('Microsoft.XMLHTTP');
request.open('GET', '/my/url');
request.onreadystatechange = function(){
  if(request.readyState == 4 && request.status == 200){
     console.log(request.responseText);
  }
}
request.send();

To further answer your question request.send() should happen last, because if the response comes back before the function is assigned to request.onreadystatechange, there could be a problem, although it's very unlikely that the response would be that fast.

StackSlave
  • 10,613
  • 2
  • 18
  • 35
  • 1
    I'm pretty in most JavaScript implementations it's simply *not possible* to get a response back before the event is bound because the events are only fired when there's nothing left for it to run. Also, I don't think the `ActiveXObject` hack is necessary since IE8+; maybe earlier. – mpen Jan 31 '14 at 01:34
  • The function assigned to `request.onreadystatechange` is fired when the `readyState` changes. `request.send()`, just sends your url info to the server, since this is a `'GET'` request. – StackSlave Jan 31 '14 at 01:47
  • I'm not sure what/if that has to do with what I just said, or how onreadystatechange + readystate==4 differs from request.onload. It appears onload is fired immediately after readyState change. http://jsfiddle.net/mnbayazit/DJY5G/4/ – mpen Jan 31 '14 at 02:03
  • `onload` is not standard for `XMLHttpRequest`s. Think Progressive Enhancement. – StackSlave Jan 31 '14 at 02:12