Reputation: 13377
Simple question. I have build this function:
// 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;
})
};
and I want to add a check to the function to be something like this:
// 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;
})
};
But I know that won't work because if there is no id then the function will no longer produce a promise. I know I could do something like this:
// 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;
})
};
but this seems like overkill. Is there an easier way to do this?
Upvotes: 2
Views: 71
Reputation: 33
You can write your function as below for shorter purpose.
// 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;
};
Upvotes: 0
Reputation: 66
From the Angular docs:
Just return $q.reject(reason)
.
This returns Promise which is instantly rejected
Upvotes: 4