deferred中done和then的區別

lethe1020發表於2018-12-27
var defer = jQuery.Deferred();

defer.done(function(a,b){
    console.log("a = "+ a+"b = "+ b);
    returna * b;

}).done(function( result ){
    console.log("result = "+ result);

}).then(function( a, b ){
    console.log("a = "+ a+"b = "+ b);
    returna * b;

}).done(function( result ){
            console.log("result = "+ result);

}).then(function( a, b ){
    console.log("a = "+ a+"b = "+ b);
    returna * b;

}).done(function( result ){
    console.log("result = "+ result);
});

defer.resolve( 2, 3);

複製程式碼

執行結果:

  • a = 2b = 3
  • result = 2
  • a = 2b = 3
  • result = 6
  • a = 6b = undefined
  • result = NaN

結論:

  • done 只是把監聽器加到promise身上,返回的是原來的promise
  • then 會把監聽器應用到promise的值,並且會建立新的promise


相關文章