2012-03-06 55 views
2

議決jQuery的遞延 - 返回承諾了一個調用鏈

我有jQuery的1.7.1與$.Deferred的問題。我認爲從when/then/fail等返回值的行爲與我認爲應該是不同的。

這就是我想要做的事:

  1. 呼叫$.when(setInstall(true)).then('do something');(這個工程,它等待Ajax請求)
  2. - >通話this.inInstallableRegion(),它運行一個Ajax請求。
  3. --->當AJAX請求成功時,我想根據AJAX請求的結果來解析或拒絕inInstallableRegion$df
  4. ---->this.inInstallableRegion已檢測到有錯誤,因此它拒絕$df的承諾(此作品),我希望它返回到setInstall我假設返回值this.inInstallableRegion$.done()作爲this.inInstallableRegion(即在這種情況下被拒絕)的結果返回。

出於某種原因,拒絕$df,但是當我去setInstall,它運行$.done功能,而不是$.fail一個:..我這麼想嗎?我不能想到一個方法來簡化它更多...我的大腦是完全油炸的:| | | | | | | | | | | | | | | | | | | | |

這些是兩個功能:

this.setInstall = function (status) { 
     $df1 = new $.Deferred(); 
     if (status === true) { 
      var self = this; 
      return $.when(this.inInstallableRegion()).done(function (json) { 
       self.setInstallDetail(json); 
       self.setDispatchCompany(); 
       $df1.resolve(); 
       return $df1.promise(); 
      }).fail(function (json) { 
       self.notifyNoInstall(json.error); 
       self.setInstall(false); 
       self.setDispatchCompany(); 
       $df1.reject(); 
       return $df1.promise(); 
      }); 
     } else { 
      this.setInstallDetail({ 
       install: 0, 
       ref_id: 0, 
       retail_price: 0 
      }); 
     } 
     this.setDispatchCompany(); 
     $df1.resolve(); 
     return $df1.promise(); 
    }; 

///////////////////////////////// ///////

this.inInstallableRegion = function() { 

    $df = new $.Deferred(); 

    var params = { 
     dataType: 'json', 
     data: $.param({ 
      'zip': this.order.delivery.zip 
     }), 
     action: 'getinstaller', 
     cache: true 
    }; 

    return $.when(this.sendData(params, 'installerCache', true)).done(function (json) { 
     if (json.error) { 
      $df.reject(); 
      return $df.promise(); 
     } else { 
      $df.resolve(); 
      return $df.promise(); 
     } 
    }); 

}; 

回答

4

我想通了。

爲了使setInstall等待inInstallableRegion完成,inIntsallableRegion必須返回一些內容。只是返回ajax請求是行不通的,因爲它會在完成時返回。根據ajax請求的結果,無論我是否想要接受或拒絕,它都不會返回。

所以我只是讓它返回它自己的延遲對象,當ajax運行和處理結果時。我在inInstallableRegion

var self = this; 
return $.Deferred(function(dfd) { 
    self.sendData(params, 'installerCache', true).then(function(json) { 
    if(json.error) { 
     dfd.reject(); 
    } else { 
     dfd.resolve(); 
    } 
    return dfd.promise(); 
    }); 
});