2017-02-21 53 views
0

我试图按照特定的顺序执行函数,但是当涉及到理解$.when()时,我遇到了问题。

function x() { 
 
    def = $.Deferred(); 
 
    $.when(def).then(console.log(def.state())); 
 
} 
 
x();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>

我的理解是,当def得到解决,则console.log(def.state())应该执行。换句话说,执行x()后不应得到任何回应,因为defpending

回答

3

then预期的回调,所以你应该创建一个包装功能:

function x() { 
    def = $.Deferred(); 
    $.when(def).then(function(){ 
    console.log(def.state()) 
    }); 
} 
x(); 
+0

解释为什么可能会有所帮助。 – Adam

1

第一:你应该解决您的Deffered。其次:你应该把一个函数传递给then方法。

function x() { 
 
    def = $.Deferred().resolve(); 
 
    $.when(def).then(function() { 
 
    console.log(def.state()); 
 
    }); 
 
} 
 
x();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>