Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/479.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 需要清除jQuery.when()_Javascript_Jquery_Typescript - Fatal编程技术网

Javascript 需要清除jQuery.when()

Javascript 需要清除jQuery.when(),javascript,jquery,typescript,Javascript,Jquery,Typescript,我有一个简单的.html页面,如下所示: </html> <head> <script type="text/javascript" src="jquery/jquery-1.8.2.js"></script> ... <script type="text/javascript"> var obj; function document_load() { obj = new mySpace.my

我有一个简单的.html页面,如下所示:

</html>
<head>

<script type="text/javascript" src="jquery/jquery-1.8.2.js"></script>
...
<script type="text/javascript">

var obj;             

function document_load() {
      obj = new mySpace.myClass(); 
      console.log("end document load");          
   }


</script>
</head>
<body onload="document_load()">
...
...
</body>
</html>
这种行为的原因当然是异步jQuery调用的原因,至少我猜是这样。我如何获得以下行为

begin constructor
here1
here2
here3
everything went ok
end document load

我澄清了JSON的使用是否正确,我试图打印它们,它们是正确的。

这是因为您没有向jQuery.when返回承诺,因此调用回调,this.obj1和this.obj2都为空

更好的方法是:

(<any>$).when(

    jQuery.getJSON('path/myJson1.json'),

    jQuery.getJSON('path/myJson2.json')

)
.then(function (obj1, obj2) {
    // Code
});

将所有函数替换为箭头函数=>。这将确保这指向所有功能体中的正确内容


更多:

我建议看一看,他确实在何时向$.when传递了承诺,但这并不能解决他回调的上下文问题。我认为问题不仅仅在于这句话。事实上,如果我试图删除if子句,控制台会打印[begin constructor,end document load,here1,here2,here3,一切正常]
begin constructor
here1
here2
here3
everything went ok
end document load
(<any>$).when(

    jQuery.getJSON('path/myJson1.json'),

    jQuery.getJSON('path/myJson2.json')

)
.then(function (obj1, obj2) {
    // Code
});