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
. 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.
(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.");
})();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.