2016-04-09 15 views
3

私は古いコードを維持していると私は、このコードに起こった:角度のjs約束が拒否されずに失敗するとどうなりますか?

var deferred = $q.defer(); 
$http.post(url,{"username": username},{cache: true}) 
      .success(function (data, status, headers, config) { 
       console.log(status); 
       console.log(headers); 
       console.log(config); 
       console.log(data); 
       deferred.resolve(data); 
      }); 

return deferred.promise; 

私はこのhttpリクエストにエラーがあるとどうなるか興味があります。 これはdeferred.rejectが呼び出されないことを意味しますか? 私は誤差関数を持っているために、これを更新する必要があります?:

 .error(function (data, status, headers, config) { 
      console.log(status); 
      console.log(headers); 
      console.log(config); 
      console.log(data); 
      deferred.reject(data); 
     }); 

答えて

0

これはDeferred anti-patternカテゴリに当たります。すべて$httpメソッドはそれ自身で約束を返します。したがって、返すだけで済むので、別の遅延オブジェクトを作成しないでください。要求が失敗すると、関数自体は拒否された約束を返します。

function saveSomething(url, username) { 
    return $http.post(url,{"username": username},{cache: true}); 
} 

// usage 
saveSomething('http://whatever', 'myUserName') 
.then(function(data) { 
    console.log(data); 
}) 
.catch(function(error) { 
    console.log(error); 
}); 
関連する問題