Promises and $q

Review

  • What is a service? What is it's purpose?
  • What is a controller? What is it's purpose?
  • How do services and controllers interact?

Review

  • What is REST?
  • How can you make an AJAX call with Angular?
  • What are promises?

Javascript is a single-threaded language

Single-Threaded

How does a single threaded language do asynchronous operations?

Event Loop

Event Loop, the queue, the stack

Javascript only does one thing at a time

However, it can pass something off and remember to do it later, once the callback is triggered 

Javascript is good at procrastinating

Promise libraries can help us to control our data

// Callback style:

$http({
  method: 'GET',
  url: '/api/users/1'
}, function(res) {
  return res.data;
})

// Promise style

$http({
  method: 'GET',
  url: '/api/users/1'
})
.then(function(res) {
  return res.data;
})

We can put the callback anywhere we need it

// In service:
this.getData = function() {

    return $http({
      method: 'GET',
      url: '/api/users/1'
    })

}

// In controller:

service.getData().then(function(data) {
  $scope.info = data;
})

Promises are 'thenable'

var promise = $http.get('/api/data/');

// The value is a promise. Promises are 'thenable'
promise.then(function(data) {
  console.log(data);
})

'.then' can be chained

var promise = $http.get('/api/data/');

// The value is a promise. Promises are 'thenable'
promise.then(function(res) {
  return res.data
})
.then(function(data) {
  // This will be the data value 
  // returned from the earlier .then callback.
  console.log(data);
})

Callbacks can get messy

step1(function (value1) {
    step2(value1, function(value2) {
        step3(value2, function(value3) {
            step4(value3, function(value4) {
                // Do something with value4
            });
        });
    });
});

Promises are much cleaner

$http.get('/api/myinfo/')
.then(promisedStep2)
.then(promisedStep3)
.then(promisedStep4)
.then(function (value4) {
    // Do something with value4
})
.catch(function (error) {
    // Handle any error from all above steps
})

Promises and $q

By Brett Caudill

Promises and $q

  • 728