在JavaScript中异步执行代码

时间:2016-03-30 13:13:54

标签: javascript angularjs mean-stack

我目前正在学习如何使用Angular.js,并尝试使用类似REST的API编写自己的身份验证代码。以下是我的身份验证服务的代码。

我的signIn函数的问题是它总是返回false,即使我的api返回HTTP 200。一段时间后,我发现由于javascript的同步特性,return response;语句在response = res.data.key;语句之前执行。

我不知道如何在分配完成后执行return语句(如果响应是HTTP 200)。我该怎么做?

angular.module('app').factory('auth', ['Base64', '$http', function(Base64, $http) {
    return {
        signIn: function(email, password) {
            var response = false;
            var encoded = Base64.encode(email + ':' + password);
            $http.defaults.headers.common.Authorization = 'Basic ' + encoded;
            $http.post('api/v1/sign_in', {}).then(function(res) {
                if (res.status == 200) {
                    response = res.data.key;
                }
            });
            return response;
        }    
    }
}]);

2 个答案:

答案 0 :(得分:2)

您需要了解承诺:从http帖子返回承诺。

This may help

答案 1 :(得分:2)

使用$q.defer()

angular.module('app').factory('auth', ['Base64', '$http', '$q', function(Base64, $http, '$q') {
    return {
        signIn: function(email, password) {
            var response = false;
            // You create a deferred object
            // that will return a promise
            // when you get the response, you either :
            // - resolve the promise with result
            // - reject the promise with an error
            var def = $q.defer();
            var encoded = Base64.encode(email + ':' + password);
            $http.defaults.headers.common.Authorization = 'Basic ' + encoded;
            $http.post('api/v1/sign_in', {}).then(function(res) {
                if (res.status == 200) {
                    response = res.data.key;
                    // success: we resolve the promise
                    def.resolve(response);
                } else {
                  // failure: we reject the promise
                  def.reject(res.status);
                }
            });
            // You return the promise object that will wait 
            // until the promise is resolved
            return def.promise;
        }    
    }
}]);

现在,你可以这样做:

auth.signIn().then(function(key) {
    // signin successful
    // do something with key
}).catch(function(err) {
    // signin failed :(
    // do something with err
}).finally(function() {
    // you could do something in case of failure and success
})