#

##

## Why Promises ?

### Let's step back to the basics

<slide>

### Single thread synchronous model aka. blocking

- Suppose a program consisting of 3 distinct tasks
- Tasks are performed one at a time
- Always in a defined order
- Simplest style of programming

<slide>

### Multi threaded model

- Tasks run in separate threads
- Threads are handled by the OS
- Threads can run concurrently
- They often end up just waiting
- Or interleaved together in single CPU
- Tasks might get suspended arbitrarily by OS
- Thread communication and synchronisation is a diffcult topic

<slide>

### Single thread asynchronous model = Javascript

- Tasks interleaved inside the same Thread
- Goodness of synchronous + multithreaded
- Programmer in control, not the OS
- Tasks are not suspended arbitrarily

<slide>

### Single thread asynchronous model = Javascript

#### The event loop handles task scheduling

    // Event loop pseudo code
    for(;;) {
      if (endOfProgram)
        quit();
      if(eventToHandle) { // task waiting, task finished ...
        handleEvent(eventToHandle); // Callback
      }
    }

<slide>

### Single thread asynchronous model = Javascript

### Therefore

- Each task must be non blocking
- Otherwise you get freezes and lags

<slide>

## Stupid Asynchronous API: Callbacks

### Asynchronous = Non Blocking

### Callbacks are a way to make tasks non blocking

            task1(function task2(task1Result) {
              // do something with task 1 result
            })

            var task1 = function(callback) {
              result = longRunningTask(); // Blocking call
              callback(result); // Calling a passed callback
            }

<slide>

## Stupid Asynchronous API: Callbacks

### Asynchronous = Non Blocking

### Callbacks are messy

            $('#button').click(function () {
              askForTwitterHandle(function(twitterHandle) {
                twitterHandle.getTweets(function (tweets) {
                  processTweets(function (processedTweets) {
                    ui.show(processedTweets);
                  });
                });
              });
            });

<slide>

### Callbacks error handling is worse, no exception propagation

            $('#button').click(function () {
              askForTwitterHandle(function(twitterHandle) {
                  twitterHandle.getTweets(function (tweets) {
                    ...
                  });
              }, function onFailure(error) {
                handleError(error);
              });
            });

### In the synchronous model we have try/catch

            try {
              handle = askForTwitterHandle();
              tweets = handle.getTweets();
              ...
            } catch (errorMessage) {
              console.log('I messed up');
            }

<slide>

## Promises are the right abstraction

#### Instead of calling a passed callback, we return a promise

            ajax('template.html', function(err, template) {
                if (err)
                  handleError();

                render(template);
            })

            // Becomes

            var promiseForTemplate = $http.get('template.html');
            promiseForTemplate.then(render, handleError)

<slide>

## Promises guarantees

              promiseForTemplate.then(onFulfilled, onFailed);

- Only one of onFulfilled or onFailed will be called
- onFulfilled will be called with a single value (return value)
- onFailed will be called with a single rejection reason (thrown exception)
- If the promise if already settled, the handlers are guaranteed to be called anyway
- The handlers will always be called asynchronousy

<slide>

## Promises can be chained

              //
              var transformedPromise = promiseForTemplate.then(onFulfilled, onFailed);

- If onFulfilled returns a value

- transformedPromise is resolved with that value

- If onFulfilled returns a promise

- transformedPromise will adapt it's state

- If onFailed throws an exception

- transformedPromise will be rejected with that exception

<slide>

## Example

### Sync

            var user = getUser();  // blocking, ie, prompt for password
            var username = user.name;

### Async with Promise

              var userNamePromise = getUser().then(function (user){
                return user.name;
              })

<slide>

## Example: throwing an exception

### Sync

            var user = getUser();  // blocking, ie, prompt for password
            if (user === null)
              throw new Error('null user');

### Async with Promise

              var userPromise = getUser().then(function (user){
                if (user === null)
                  throw new Error('null user');
                return user;
              })

<slide>

## Example: handling an exception

### Sync

            try {
              updateUser(data);
            } catch (exp) {
              console.log('There was an error', exp);
            }

### Async with Promise: exception propagation

              var updateUserPromise = updateUser(data).then(undefined, function(exp) {
                console.log('There was an error', exp);
              })

<slide>

## Example: rethrowing an exception

### Sync

            try {
              updateUser(data);
            } catch (exp) {
              throw new Error('UpdateUserError: ' + exp.message)
            }

### Async with Promise: exception propagation

            var updateUserPromise = updateUser(data).then(undefined,  function(exp) {
              throw new Error('UpdateUserError: ' + exp.message)
            })

<slide>

## Example: exception propagation

### Callbacks

              getUser('spike', function(err, user){
                if(err) {
                  ui.error(err);
                } else {
                  getBestFriend(user, function(err, friend){
                    if (err) {
                      ui.error(err);
                    } else {
                      ui.showBestFriend(friend, function(err, friend){
                        if (err) {
                          ui.error(err);
                        }
                      })
                    }
                  })
                }
              })

<slide>

## Example: exception propagation

### Promises

              getUser()
              .then(getBestFriend)
              .then(ui.showBestFriend)
              .then(undefined, ui.error)

<slide>

## Promises in Angular

- Provided by $q service
- Inspired by the the promise/deferred `Q library`
- Is a lightweight implementation of Promises (Q is much more complete)
- Promises are used everywhere Angular needs async

- $http
- $resource
- $routeProvider
- Controller properties
- Response Interceptors
- ...

- Optimized for the Angular run loop

<slide>

## Angular Run Loop

<slide>

## How to use Promises in Angular

              .controller('testCtrl', function($scope, $q) { // inject the service

                var promiseOfTask = function () {

                  var deferredTask = $q.defer(); // create a deferred object

                  var result = blockingTask(); // long running task
                  deferredTask.resolve(result) // resolve the future promise with the result

                  return deferredTask.promise // return the promise
                }

                //using the promise
                promiseOfTask().then(function(result){
                  $scope.updateSomeModel(result);
                })
              })

## Demonstration

### Handling failovers for api calls

<slide>

## Slide with Bullets that Build

### Subtitle Placeholder

A list where items build:

- Pressing 'h' highlights code snippets
- Pressing 'p' toggles speaker notes (if they're on the current slide)
- Pressing 'f' toggles fullscreen viewing
- Pressing 'w' toggles widescreen
- Pressing 'o' toggles overview mode
- Pressing 'ESC' toggles off these goodies

Another list, but items fade as they build:

- Hover over me!
- Hover over me!
- Hover over me!

<slide>

## Slide with (Smaller Font)

- All links open in new tabs.
- To change that this, add `target="_self"` to the link.

<slide hidden> Hidden slides are left out of the presentation. <slide>

## Code Slide (with Subtitle Placeholder)

### Subtitle Placeholder

Press 'h' to highlight important sections of code (wrapped in `<b>`).

    <script type='text/javascript'>
      // Say hello world until the user starts questioning
      // the meaningfulness of their existence.
      function helloWorld(world) {
        for (var i = 42; --i >= 0;) {
          alert('Hello ' + String(world));
        }
      }
    </script>

<slide>

## Code Slide (Smaller Font)

    // Say hello world until the user starts questioning
    // the meaningfulness of their existence.
    function helloWorld(world) {
      for (var i = 42; --i >= 0;) {
        alert('Hello ' + String(world));
      }
    }

    <style>
      p { color: pink }
      b { color: blue }
    </style>

    <!DOCTYPE html>
    <html>
    <head>
      <title>My Awesome Page</title>
    </head>
    <body>
      <p>Hello world</p>
    <body>
    </html>

<slide>

- Point I wanted to make #1
- Point I wanted to make #2
- Point I wanted to make #3
- Example link in notes.

Remember to say this tag line!

## Slide with Speaker Notes

Press 'p' to toggle speaker notes.

<slide>

- See this amazing link: link.

Remember to say this tag line!

## Presenter Mode

Add `?presentme=true` to the URL to enabled presenter mode. This setting is sticky, meaning refreshing the page will persist presenter mode.

Hit `?presentme=false` to disable presenter mode.

<slide>

## Slide with Image

<slide>

## Slide with Image (Centered horz/vert)

<slide>

## Table Option A

### Subtitle Placeholder

| Column 1 | Column 2 | Column 3 | Column 4
--- | --- | --- | --- | ---
Row 1 | placeholder | placeholder | placeholder | placeholder
Row 2 | placeholder | placeholder | placeholder | placeholder
Row 3 | placeholder | placeholder | placeholder | placeholder
Row 4 | placeholder | placeholder | placeholder | placeholder
Row 5 | placeholder | placeholder | placeholder | placeholder

<slide>

## Table Option A (Smaller Text)

### Subtitle Placeholder

| Column 1 | Column 2 | Column 3 | Column 4
--- | --- | --- | --- | ---
Row 1 | placeholder | placeholder | placeholder | placeholder
Row 2 | placeholder | placeholder | placeholder | placeholder
Row 3 | placeholder | placeholder | placeholder | placeholder
Row 4 | placeholder | placeholder | placeholder | placeholder
Row 5 | placeholder | placeholder | placeholder | placeholder

<slide>

## Table Option B

### Subtitle Placeholder

Header 1 | placeholder | placeholder | placeholder
Header 2 | placeholder | placeholder | placeholder
Header 3 | placeholder | placeholder | placeholder
Header 4 | placeholder | placeholder | placeholder
Header 5 | placeholder | placeholder | placeholder

<slide>

## Slide Styles

- class="red"
- class="red2"
- class="red3"
- class="blue"
- class="blue2"
- class="blue3"
- class="green"
- class="green2"

- class="green3"
- class="yellow"
- class="yellow2"
- class="yellow3"
- class="gray"
- class="gray2"
- class="gray3"
- class="gray4"

I am centered text with a
and
button.

## Segue Slide

### Subtitle Placeholder

## Full Image (with Optional Header)

This is an example of quote text.
Name
Company
<slide>

## Slide with Iframe

<slide>

## <Thank You!>

Important contact information goes here.