2

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?

3 Answers 3

4

From the Angular docs:

Just return $q.reject(reason). This returns Promise which is instantly rejected

Sign up to request clarification or add additional context in comments.

Comments

1

you can simply use

$q.reject();

Comments

0

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;
};

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.