var d1 = $.Deferred();
var variable = false;
$.when(function(){
console.log("This should be printed(consoled) first!");
if(variable == false){
variable = true;
d1.resolve();
}else{
d1.resolve();
}
return d1.promise();
}).then(function(callback){
console.log("The variable should be true: -> " + variable);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
"$.when"中的函数应该在"then"中的函数之前执行,它应该将变量的值设置为"true"。但是有一个问题,由于某种原因它不起作用。
最佳答案
您放置在 $.when
中的匿名函数永远不会执行,因此永远不会返回 promise 。
如果你真的执行了这个函数,那么 promise 就返回了,它工作正常
var d1 = $.Deferred();
var variable = false;
$.when((function(){ // using an IIFE
console.log("This should be printed(consoled) first!");
if(variable == false){
variable = true;
d1.resolve();
}else{
d1.resolve();
}
return d1.promise();
})()).then(function(callback){
console.log("The variable should be true: -> " + variable);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
关于javascript - 为什么 jquery "when promise"在此代码段中不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46553080/