在这个javascript中有没有竞争条件? [英] is there a race condition in this javascript?

查看:107
本文介绍了在这个javascript中有没有竞争条件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在以下js代码段

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

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

如果负载的分配在send()之前,以避免竞争条件。

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).

推荐答案

您的浏览器可以处理您的邮件请求应该看起来更像:

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();

要进一步回答您的问题 request.send()应该最后发生,因为如果响应回来之前函数被分配到 request.onreadystatechange ,可能有一个问题,虽然不太可能的响应将是那快。

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.

这篇关于在这个javascript中有没有竞争条件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆