Skip to content

Instantly share code, notes, and snippets.

@adgllorente
Created February 21, 2016 22:07
Show Gist options
  • Save adgllorente/9c93cfac7ffa6f666b62 to your computer and use it in GitHub Desktop.
Save adgllorente/9c93cfac7ffa6f666b62 to your computer and use it in GitHub Desktop.
chaining-promises
/**
* Obtains a user from its email
* @param {string} email Email to get the user.
* @return {Promise} To be resolved with a user or an error code.
*/
function getUser(email) {
return api.getUser(email)
.then(function(user) {
return user || $q.reject(ERROR_CODE.USER_NOT_EXISTS);
});
.catch(function() {
return $q.reject(ERROR_CODE.API_ERROR);
});
}
/**
* Enables the user
* @param {Object} user User to enable.
* @return {Promise} To be resolved with a user or rejected with an error code.
*/
function enableUser(user) {
return api.enableUser(user)
.catch(function() {
return $q.reject(ERROR_CODE.API_ERROR);
});
}
/**
* Obtains a token from a given user.
* @param {Object} user User to obtain the token
* @return {Promise} To be resolved with a token or rejected with an error code.
*/
function getUserToken(user) {
return api.getUserToken(user)
.then(function() {
return token || $q.reject(ERROR_CODE.INVALID_TOKEN);
})
.catch(function() {
return ERROR_CODE.API_ERROR;
});
}
/**
* Activates a user an obtains a token.
* @param {string} email Email to activate the user
* @return {Promise} To be resolved with a token or rejected with an error code.
*/
function activate(email) {
return !email ?
$q.reject(ERROR_CODE.NOT_VALID_PARAMS) :
getUser(email)
.then(enableUser)
.then(getUserToken);
}
/**
* Manages an error showing a log.
* @param {number} error Error to manage.
*/
function manageError(error) {
switch(error) {
case ERROR_CODE.NOT_VALID_PARAMS:
console.error('Params are not valid');
break;
case ERROR_CODE.USER_NOT_EXISTS:
console.error('User not exists');
break;
case ERROR_CODE.INVALID_TOKEN:
console.error('Token is invalid');
break;
case ERROR_CODE.API_ERROR:
console.error('API has failed');
break;
}
}
/**
* Main function
*/
function main() {
activate(email)
.then(function(token) {
$scope.token = token;
})
.catch(manageError);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment