2016-08-11 6 views
0

좋아하는 위치 목록을 반환해야하는 기능이 있습니다. 이 같은 것

LocationsFactory.getFavoriteLocations(). then (function ($ favoriteLocations) { });

getFavoriteLocations는 약속에 따라 함수의, 다시

getFavoriteLocations: function() { 
       if (favorite_locations.length == 0) 
       { 
        var deff = $q.defer(); 
        obj.getDeviceId().then(function(device_id) { 
        $http.get('url?token=' + device_id).then(function(response) { 
           favorite_locations = response.data; 
           deff.resolve(favorite_locations); 
           return deff.promise; 
           }) 
        }) 
       } else { 
        return favorite_locations; 
       } 
      } 

getDeviceId 같이 보입니다.

getDeviceId: function() { 
    var deff = $q.defer(); 
    deff.resolve(Keychain.getKey()); 
    return deff.promise; 
} 

오류가 발생했습니다. TypeError : 정의되지 않은 'then'속성을 읽을 수 없습니다. 도와주세요! 여기에 필요하지 않습니다에

+0

당신은 반환 $의 q.resolve'와 약속을 반환 할 수 있습니다 (Keychain.getKey는())' – karaxuna

+0

당신은'에있다 'getFavoriteLocations'에서'deff.promise;를 리턴하십시오. – str

답변

0

당신은 체인 약속 할 수

 getFavoriteLocations: function() { 
      if (favorite_locations.length === 0) { 
       return obj.getDeviceId().then(function (device_id) { 
        return $http.get('url?token=' + device_id).then(function (response) { 
         favorite_locations = response.data; 
         return favorite_locations; 
        }); 
       }); 
      } 

      return $q.resolve(favorite_locations); 
     } 

그리고이 개선 :

getDeviceId: function() { 
    return $q.resolve(Keychain.getKey()); 
} 
+2

중첩 약속은 IMO가 아주 좋은 습관은 아닙니다. –

0

$q :

if (favorite_locations.length == 0) 
{ 
    return obj.getDeviceId() // you have to return a promise here 
     .then(function(device_id) { 
      return $http.get('url?token=' + device_id) // you will access the response below 
     }) 
     .then(function(response) { 
      favorite_locations = response.data; 
      return favorite_locations 
     }); 
    }) 
} 

이 지금은 작동합니다.