AngularJS函数返回带有必需参数的promise

时间:2016-02-17 15:21:00

标签: angularjs angular-promise

简单的问题。 我已经建立了这个功能:

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

但我知道这不会起作用,因为如果没有id,那么该函数将不再产生一个承诺。 我知道我可以这样做:

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

但这似乎有点矫枉过正。 有更简单的方法吗?

3 个答案:

答案 0 :(得分:4)

来自Angular docs

只需return $q.reject(reason)。 这会返回即时被拒绝的Promise

答案 1 :(得分:1)

你可以简单地使用

$q.reject();

答案 2 :(得分: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;
};