简体   繁体   English

为什么这个承诺调用之后的代码不运行?

[英]Why doesn't the code after this promise invocation run?

When I try to add any code after handing a function to a promise to run when it finishes, it never runs. 当我在将函数交给完成后要运行的承诺后尝试添加任何代码时,它将永远不会运行。 See this example. 请参阅此示例。

(function() {
   var url = //some url that I know works

   var promise = $.get(url);
   $.when(promise).then(function(xml) {
      alert("Promise resolved.");
   })();

   //This code doesn't run!
   alert("Code after promise.");
})();

I thought that execution immediately went to the next line after $.when . 我认为$.when之后,执行立即转到下一行。 Isn't that the whole point of using promises? 这不是使用诺言的全部意义吗? The "Promise resolved" alert goes off fine, but the "Code after promise" never appears. “已解决承诺”警报运行良好,但是“承诺后代码”从未出现。 What am I missing? 我想念什么?

You have an unnecessary () after this block: 在此块之后,您有一个不必要的()

$.when(promise).then(function(xml) {
    alert("Promise resolved.");
  })();

Change it to: 更改为:

$.when(promise).then(function(xml) {
    alert("Promise resolved.");
  });

One of the comments stated that you need a $ at the beginning of your code. 其中一条注释指出,在代码开头需要$ This is not true. 这不是真的。 You are simply creating a closure here, and this is perfectly acceptable syntax for such. 您只是在这里创建一个闭包,这是完全可以接受的语法。 I would, however, recommend prefixing your script with a ; 但是,我建议您在脚本前加上; so that if it is included after any other closures, it ensures that they are closed. 因此,如果将其包含在其他任何闭包之后,则可以确保将其关闭。 This is just generally good practice when using closures in JavaScript. 在JavaScript中使用闭包时,通常这只是一个好习惯。

(function(){
   var url = //some url that I know works

   var promise = $.get(url);
   //********************************
   $.when(promise).then(function(xml){
   alert("Promise resolved.");
   }); // take this () off
   //********************************
   //This code will run first
   alert("Code after promise.");
 })();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM