General Assembly

Asynchronous JavaScript & Callbacks

Wilson Espina

Review

What did we do last lesson?

Asynchronous JavaScript

Learning Objective

Learning Objectives

At the end of this class, you will be able to:

  • Describe what asynchronous means in relation to JavaScript
  • Pass functions as arguments to functions that expect them.
  • Write functions that take other functions as arguments.
  • Build asynchronous program flow using Fetch

Asynchronous JavaScript

Exit Ticket Questions

  1. The code-alongs required lots of writing syntax - Can we have this beforehand?

Asynchronous JavaScript

Agenda

  • Asynchronous Programming
  • Functions & Callbacks
  • Promises

Asynchronous JavaScript

Classroom Resources

  • Pull changes from the wilson-espina/jsd-9-resources repo to your computer
  • In your editor, open the following folder: Documents/JSD/jsd-9-resources/11-async-callbacks

Asynchronous JavaScript

Asynchronous Programming

Asynchronous JavaScript

Synchronous Code


let status
function doSomething() {
    for (let i	= 0; i < 1000000000; i++) {
        numberArray.push(i)
    }
    status = 'done'
    console.log('First function done')
}
function doAnotherThing() {
    console.log('Second function done')
}
function doSomethingElse() {
    console.log('Third function: '+ status)
}
								

doSomething()

doAnotherThing()

doSomethingElse()


// result in console
// (after a few seconds):

> "First function done"
> "Second function done"
> "Third function: done"
									

Asynchronous JavaScript

Synchronous Code

  • Statements are executed in order, one after another.
  • Code blocks program flow to wait for results.
  • Most JavaScript code is synchronous.
Statements blocks synchronous

Asynchronous JavaScript

Asynchronous Code

  • Code execution is independent of the main program flow.
  • Statements are executed concurrently.
  • Program does not block program flow to wait for results.
  • Certain JS statements are asynchronous by default.
Statements blocks asynchronous

Asynchronous JavaScript

Asynchronous Program Flow


$('button').on('click', doSomething);

$.ajax(url, function(data) {
    doAnotherThing(data)
});

fetch(url).then(response => {
    if (response.ok) {
	    return response.json();
    } else {
        console.log('There was a problem.');
    }
}).then(doSomethingElse);
							

Asynchronous JavaScript

Approaches to Asynchronous Program Flow

Asynchronous flow options

Ajax & APIs

Functions & Callbacks

Asynchronous JavaScript

How many arguments in this code?


$('button').on('click', function() {
	// your code here
});
							

								$('button').on(argument1, argument2);
							

Asynchronous JavaScript

Approaches to Asynchronous Program Flow

Asynchronous flow options 1

Asynchronous JavaScript

Functions are first-class objects

  • Can store a function as a variable value.
  • Can return a function from another function.
  • Can pass a function as an argument to another function.

Asynchronous JavaScript

Functions are first-class objects

  • Can store a function as a variable value.

const getWeather = (weatherUrl, city, apiKey) => {
    $.ajax({
        url: weatherUrl + city + '&appid=' + apiKey,
        success: function (response) {
            updateUISuccess(response.main.temp)
        },
        error: function () {
            updateUIError();
        },
    });
};
							

Asynchronous JavaScript

Functions are first-class objects

  • Can return a function from another function.

const programmeModule = (() => {
    let programmes = [];
    return {
        addProgramme: function(newProgramme) {
            programmes.push(newProgramme);
        },
        getProgrammes: function() {
            return programmes
        }
    }
})()
						

Asynchronous JavaScript

Functions are first-class objects

  • Can pass a function as an argument to another function.

function helloWorld() {
    console.log("Hello world");
}

setTimeout(helloWorld, 1000);
							

Asynchronous JavaScript

Higher-Order Function

  • A function that takes another function as an argument, or that returns a function.
Higher order functions

Asynchronous JavaScript

Higher-Order Function - Example

setTimeout()


setTimeout(function, delay);
						
  • function is a function(reference or anonymous.
  • delay is a time in milliseconds to wait before the first argument is called.

Asynchronous JavaScript

Settimeout


setTimeout(() => {
  console.log("Hello world")
}, 1000);
							

setTimeout with anonymous function argument


function helloWorld() {
  console.log("Hello world");
}

setTimeout(helloWorld, 1000);
							

setTimeout with named function argument

Asynchronous JavaScript

Callbacks

Callback 1 Callback 2

Asynchronous JavaScript

Callbacks

  • A function that is passed to another function as an argument, and that is then called from within the other function.
  • A callback function can be anonymous (as with setTimeout() or forEach()) or it can be a reference to a function defined elsewhere.

Code along

Code Along

Open up: 00-callback-codealong

Code Along

Activity - Callback Exercise

Exercise

Objective

  • Create callback functions

Location

  • starter-code > 01-callback-exercise

Timing

20 mins

  1. In your editor, open script.js.
  2. Follow the instructions to create the add, showAnswer, calcResult, and subtract functions, and to call the calcResult function using the add and subtract functions as callbacks.
  3. Test your work in the browser and verify that you get the expected results.
  4. BONUS: Update the showAnswer function to change the content of the element with the id value 'operator' to a plus symbol after the user clicks the Add button, or to a minus symbol after the user clicks the Subtract button.

Ajax & APIs

Promises

Asynchronous JavaScript

Callback Hell


doSomething((result) => {
  doSomethingElse(result, (newResult) => {
    doThirdThing(newResult, (finalResult) => {
      console.log('Got the final result: ' + finalResult);
    }, failureCallback);
  }, failureCallback);
}, failureCallback);
							

Asynchronous JavaScript

Approaches to Asynchronous Program Flow

Asynchronous flow options 2

Asynchronous JavaScript

Promises

Traditional Callback:


doSomething(successCallback, failureCallback);
							

Callback using a promise:


doSomething()
  .then(successCallback)  // work with result
  .catch(failureCallback) // handle error
							

Asynchronous JavaScript

Multiple Callbacks with Promises


doSomething()
  .then(result1 => doSomethingElse(result1))
  .then(result2 => doThirdThing(result2))
  .then(result3 => {
    console.log('Got the final result: ' + result3)
  })
  .catch((error) => {
    console.log('There was an error: ' + error);
  });
							

Asynchronous JavaScript

Error Handling with Promises

Promises error handling

Asynchronous JavaScript

Creating Promises



const fooPromise = () => {
  return new Promise(function(resolve, reject) {




  });
}

							

Asynchronous JavaScript

Creating Promises



const fooPromise = () => {
  return new Promise(function(resolve, reject) {
	if (/* everything turned out fine */) {
	  resolve("Stuff worked!");
	} else {
	  reject(Error("It broke"));
	}
  });
}

							
  • Resolve and Reject are callbacks

Asynchronous JavaScript

Creating Promises - SetTimeout



const fooPromise = () => {
  return new Promise(function(resolve, reject) {
    setTimeout(() => {
      resolve('foo')
    }, 5000)
  });
}

fooPromise()
  .then(value => {
  console.log(value) /* expected output: "foo" */
});

							

Asynchronous JavaScript

Promises

At any stage, a Promise will be in one of these 4 states:

  • Pending: Initial state, not fulfilled or rejected.
  • Fulfilled: operation completed successfully.
  • Rejected: operation failed.
  • Settled: It has been fulfilled or rejected already.
Promises flow diagram

Asynchronous JavaScript

Fetch with Promises


fetch(url)
  .then(function (response) {
    if (response.ok) {
      return response.json();
    } else {
      throw 'Network response was not ok.';
    }
  }).then(function (data) {
    // DOM manipulation
  }).catch(function (error) {
    // handle lack of data in UI
});

							

Asynchronous JavaScript

Error Handling for Initial Fetch Request

Error handling for initial fetch request

Code along

Code Along

Open up: 02-fetch-codealong

Code Along

Lab - Async

Exercise

Location

  • starter-code > 03-async-lab

Timing

20 mins

  1. In your editor, open script.js.
  2. Follow the instructions to add a Fetch request for weather data that uses the results of the existing post lookup.

Asynchronous JavaScript

Learning Objective

Learning Objectives - Review

  • Describe what asynchronous means in relation to JavaScript
  • Pass functions as arguments to functions that expect them.
  • Write functions that take other functions as arguments.
  • Build asynchronous program flow using Fetch.

Asynchronous JavaScript

Look Ahead to Next Lesson

  • Request data from Google Maps and TFL web services.
  • Implement the geolocation API to request a location.
  • Use Postman to construct and test an API request.
  • Process a third-party API response and share location data on your website.
  • Search documentation needed to make and customise third-party API requests.

Asynchronous JavaScript

Homework

Asynchronous JavaScript

Exit Ticket

(Lesson #11)