简体   繁体   English

链接2 HTTP请求并返回第二个Promise

[英]Chain 2 HTTP requests and return 2nd promise

Before making an HTTP request, I need to check if the access credentials I have are valid. 在发出HTTP请求之前,我需要检查我拥有的访问凭据是否有效。 If they are not valid, I need to make a first HTTP request to revalidate them and, after completion, then a second HTTP request (the original one). 如果它们无效,我需要发出第一个HTTP请求以重新验证它们,完成后,再发出第二个HTTP请求(原始请求)。 The function call needs to return Angular's $http promise from the second HTTP request. 该函数调用需要从第二个HTTP请求返回Angular的$http Promise。 Here's my function: 这是我的功能:

var makeRequest = function (scope, address, request, basic, form) {

        startLoad(scope); 

        // Check if user is logged in and needs a new session token...
        if (ready() && (now() > getSessionExpires()-20) ) {

            // Setup auth.session.refresh request
            var refreshRequest = {
                "refreshToken": getRefreshToken(),
                "clientID": getClientID(),
            };

            // Make auth.session.refresh request
            $http.post(API + 'auth.session.refresh', format(refreshRequest))
                .error(function (data) {
                    // If refresh request fails, logout and redirect to expired message
                    stopLoad(scope); logoff();
                    $window.location.href = '/error/expired';
                    return;
                })
                .success(function (data) {
                    // If refresh request succeeds, makeRequest is called recursively and the else condition runs
                    process(data, true);
                    return makeRequest(scope, address, request, basic, form);
                });

        } else { // if not logged in, or if session token is valid, run request function as usual

            // Add Authorization header with valid sessionToken
            if (ready()) $http.defaults.headers.post['Authorization'] = 'Bearer ' + getSessionToken();

            // Basic Request: returns promise (if next context not set, can chain other action)
            if (basic) {
                return $http.post(API + address, request)
                    .error(function(data) {

                        if (data && scope) stopLoad(scope, data.message);
                        else if (scope) stopLoad(scope, Defaults.serverError);
                        else stopLoad();

                        if (form) resetForm(form);
                     })
                    .success(function(data) {
                        process(data);

                        if (scope) {
                            stopLoad(scope);
                            if (scope.context.next) $location.path(scope.context.next);
                        } else stopLoad();

                        if (form) resetForm(form);
                    });
            }

            // Custom Request: returns promise (can chain .error, .success)
            else return $http.post(API + address, request);
        }
    };

When the token is found to be invalid, however, the function returns undefined, and I get an error that I cannot run .success() or .error(). 但是,当发现令牌无效时,该函数将返回未定义的消息,并且出现错误,我无法运行.success()或.error()。 The else functionality runs, but I'm wondering how I can ensure that I don't get this error. else功能可以运行,但是我想知道如何确保不会出现此错误。 Thank you! 谢谢!

Just return the upper $http.post(/*...*/) and let promise chaining do it's magic: 只需返回上面的$http.post(/*...*/)并让诺言链做起来很神奇:

    return $http.post(API + 'auth.session.refresh', format(refreshRequest))
                    .catch(function (response) {
                        // If refresh request fails, logout and redirect to expired message
                        stopLoad(scope); logoff();
                        $window.location.href = '/error/expired';
                    })
                    .then(function (response) {
                        // If refresh request succeeds, makeRequest is called recursively and the else condition runs
                        process(response.data, true);
                        return makeRequest(scope, address, request, basic, form);
                    });

UPDATE: since .success / .error functions are not chainable (and have been flagged deprecated ), you should use .then and .catch instead. 更新:由于.success / .error功能没有可链接(并已被标记弃用 ),你应该使用.then.catch代替。

$http.post(/*...*/)
    .success(function(data) {
        /* do something with data */
    })
    .error(function(err) {
        /*...*/
    });

becomes 变成

$http.post(/*...*/)
    .then(function(response) {
        /*do something with response.data */
    })
    .catch(function(response) {
        /*...*/
    });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM