簡單的問題。 我建立這個功能: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;
})
};
但這似乎是大材小用。 有沒有更簡單的方法來做到這一點?