gumatias
12/30/2015 - 2:39 PM

promises vts blog post

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
}