Currently, I am in the process of learning Angular.js and decided to create my own authentication code using a REST-like API. Below you can find the implementation of my authentication service.
The main issue with my signIn
function is that it consistently returns false, even when the API responds with an HTTP 200
status. After some investigation, I realized that this happens due to the synchronous nature of JavaScript, where the return response;
statement gets executed before response = res.data.key;
.
I am puzzled about how to make the return statement wait until the assignment operation is completed (in case the response is indeed HTTP 200
). How can I achieve this?
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;
}
}
}]);