Skip to content

Instantly share code, notes, and snippets.

@adgllorente
Created February 21, 2016 22:08
Show Gist options
  • Save adgllorente/4f5b45385b3800b9e28c to your computer and use it in GitHub Desktop.
Save adgllorente/4f5b45385b3800b9e28c to your computer and use it in GitHub Desktop.
chaining-promises
/**
* 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) {
var defer = $q.defer();
if (!email) {
// 1. Check params
defer.reject(ERROR_CODE.NOT_VALID_PARAMS);
} else {
// 2. Get User
api.getUser(email).then(
function(user) {
if (!user) {
defer.reject(ERROR_CODE.USER_NOT_EXISTS);
} else {
// 3. Enables the user
api.enableUser(user).then(
function(user) {
// 4. Obtains a token for the user.
api.getUserToken(user).then(
function(token) {
if (token) {
// Return obtained token.
defer.resolve(token);
} else {
defer.reject(ERROR_CODE.INVALID_TOKEN);
}
}, function() {
defer.reject(ERROR_CODE.API_ERROR);
}
);
}, function() {
defer.reject(ERROR_CODE.API_ERROR);
}
);
}
}, function() {
defer.reject(ERROR_CODE.API_ERROR)
}
);
}
return defer.promise;
}
/**
* 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