Created
February 21, 2016 22:08
-
-
Save adgllorente/4f5b45385b3800b9e28c to your computer and use it in GitHub Desktop.
chaining-promises
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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