Created
December 30, 2015 14:39
-
-
Save gustiando/c044c483d2e6f42be38a to your computer and use it in GitHub Desktop.
promises vts blog post
This file contains hidden or 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
// This is my task requested by mom every time we would go grocery shopping | |
function checkCookiePrice() { | |
var defer = $q.defer(); | |
setTimeout(function () { | |
// very random. I could only believe in God back then... | |
var random = Math.floor(Math.random() * 3); | |
if (random == 0) | |
// YES! | |
defer.resolve('cheap'); | |
else if (random == 1) | |
// Well, guess I'll be eating lots of cream crackers... | |
defer.resolve('expensive'); | |
else | |
// something bad happened, oh boy.. | |
defer.reject(); | |
}, 1000); // I would definitely take longer than a second. But this is just for demonstration purposes. | |
return defer.promise; | |
} | |
// This is mom's task | |
function doShopping() { | |
checkCookiePrice() | |
.then(function (kidResponse) { // first arg is a resolved promise | |
if (kidResponse === 'cheap') | |
$scope.momSays = "OK, we can buy it..."; | |
else if (kidResponse === 'expensive') | |
$scope.momSays = "Are you crazy?! that's worth one kilo of rice and beans!"; | |
}, function () { // second arg is a rejected promise | |
// Unexpected occurrence. Fortunately this was never the case | |
$scope.momSays = "Where's my kid?!?!"; | |
}); | |
// ... Mom would keep on shopping while I'd be asynchronously working on her request | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment