jQuery.when() 需要清除

jQuery.when() need to be cleared up

本文关键字:清除 when jQuery      更新时间:2023-09-26

我有一个简单的.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>

myClass 是一个具有此构造函数的 TypeScript 类:

 public constructor() {
    console.log("begin constructor");
    (<any>$).when(
      jQuery.getJSON('path/myJson1.json', function (data) {
       this.obj1 = data;
       console.log("here1");
        }),
       jQuery.getJSON('path/myJson2.json', function (data) {
       this.obj2 = data;
       console.log("here2");
        })
       ).then(function () {
          if (this.obj1 && this.obj2) {
           console.log("here3");
           this.obj3 = new myClass3();
           this.obj4 = new myClass4(); 
           console.log("everything went ok");
        }
     });
   } 

实际上控制台打印了这个:

begin constructor
end document load
here1
here2

这种行为的原因(当然)是异步jQuery调用的原因(或者至少我猜是这样)。如何获得以下行为?

begin constructor
here1
here2
here3
everything went ok
end document load

我澄清了 json 是正确的(我试图打印它们并且它们是正确的)。

这是因为您没有向jQuery.when返回承诺,因此调用回调并且this.obj1 && this.obj2都是null。

更好的方法是:

(<any>$).when(
    jQuery.getJSON('path/myJson1.json'),
    jQuery.getJSON('path/myJson2.json')
)
.then(function (obj1, obj2) {
    // Code
});

将所有函数替换为箭头函数 (=>)。这将确保"this"指向所有函数体中的正确事物。

更多 : https://www.youtube.com/watch?v=tvocUcbCupA