Skip to content

Instantly share code, notes, and snippets.

@gumatias

gumatias/promise.js

Created Dec 30, 2015
Embed
What would you like to do?
promises vts blog post
// 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