2016-02-17 54 views
2

簡單的問題。 我建立這個功能:AngularJS函數返回承諾與所需參數

// Gets the kit by id or slug 
var _getKit = function (id) { 

    // Try to get our kit using our shared service 
    return sharedKitService.get(id).then(function (response) { 

     // Assign the response to our service 
     service.models.kit = response; 

     // Return our response 
     return response; 
    }) 
}; 

,我想檢查添加的功能是這樣的:

// Gets the kit by id or slug 
var _getKit = function (id) { 

    // If we have no id, exit the function 
    if (!id) 
     return; 

    // Try to get our kit using our shared service 
    return sharedKitService.get(id).then(function (response) { 

     // Assign the response to our service 
     service.models.kit = response; 

     // Return our response 
     return response; 
    }) 
}; 

但我知道,如果沒有,不會因爲工作然後該函數將不再產生承諾。 我知道我可以做這樣的事情:

// Gets the kit by id or slug 
var _getKit = function (id) { 

    // If we have no id 
    if (!id) { 

     // Defer our promise 
     var deferred = $q.derfer(); 

     // Reject our promise 
     deferred.reject(); 

     // Return our promise 
     return deferred.promise; 
    } 

    // Try to get our kit using our shared service 
    return sharedKitService.get(id).then(function (response) { 

     // Assign the response to our service 
     service.models.kit = response; 

     // Return our response 
     return response; 
    }) 
}; 

但這似乎是大材小用。 有沒有更簡單的方法來做到這一點?

回答

4

Angular docs

只是return $q.reject(reason)。 這會返回即時被拒絕的Promise

1

,你可以簡單地使用

$q.reject(); 
0

您可以按照以下方式編寫函數以達到較短的目的。

// Gets the kit by id or slug 
var _getKit = function (id) { 
    var deferred = $q.defer(); 
    // If we have no id 
    if (!id) { 
     // Reject our promise 
     deferred.reject(); 
    } else { 
     sharedKitService.get(id).then(function (response) { 
      // Assign the response to our service 
      service.models.kit = response; 

      // Return our response 
      deferred.resolve(response); 
     }); 
    } 
    return deferred.promise; 
};