JS-151-API
  • JavaScript Library
  • 02-DOM-Manipulation
    • Overview
    • DOM Explained
    • Example Setup
    • Selecting Elements
    • Events
    • Complete Example
  • 03-API Fundamentals
    • 0-Getting Started
      • Welcome
    • 1-Intro-To-APIs
      • Intro
      • Client
      • Requests
      • JSON
      • API Endpoints
      • Server
      • Response
      • Statelessness
      • REST
    • 2-Asynchronous-Programming
      • Intro
      • Callbacks
      • Promises
      • Promises Continued
      • Chaining Promises
    • 3-Fetch
      • Fetch Intro
      • Star Wars
        • Star Wars API
        • Star Wars Setup
        • Star Wars JS
      • Random Photo
        • Unsplash
        • Unsplash Setup
        • Unsplash JS
    • 4-Apps
      • 01-New York Times
        • 00-App Intro
        • 01-HTML/CSS/API Key
        • 02-Variables
        • 03-Event Listeners
        • 04-fetchResults
          • 01-fetchResults()
          • 02-preventDefault()
          • 03-fetch() method
          • 04-Dates
        • 05-displayResults
          • 01-Logging JSON
          • 02-Working with JSON
          • 03-Link Display
          • 04-Results Navigation
          • 05-Results Update
          • 06-Keywords
          • 07-Images
        • 06-Pagination
          • 01-Pagination Intro
          • 02-Pagination Functions
        • 07-Next Steps
      • 02-YouTube
        • html
        • youtube.css
        • youtube.js
      • 03-GoogleMaps
        • Setup
        • HTML and CSS files
        • API Key
        • JS Setup
        • Adding Your Location
        • Listeners
        • Custom Options
Powered by GitBook
On this page
  1. 03-API Fundamentals
  2. 2-Asynchronous-Programming

Callbacks

A callback function is function executed by another function. Usually this occurs when data needs to be processed or modified in some way so that it can be used later within the original function.

Whew! what does that mean? Let's explore this with some code examples.

function callbackFunction(){
    const data = {
        name: 'Ralf Machio', 
        age: 66, 
        occupation: 'kickboxing'
    }
    return data;
}

function showGreeting(dataFromFunction){
    return "hello " + dataFromFunction.name + ", I hear you're the greatest?!"
}

console.log(
    showGreeting(callbackFunction())
)

We see that in the showGreeting(callbackFunction()) line of code, we are invoking the function that we created above called callbackFunction().

The purpose of our showGreeting() function is to return a string that is built with data that will be coming from our argument.

But what if that data needs to be built first?

That's where we create a function that can run a series of operations to take in values and give us something new. In this case, the callbackFunction is returning us a object with 3 properties:

  • name

  • age

  • occupation

We can then access them in our original showGreeting() function.

By us passing the callbackFunction() as an argument in the showGreeting(), we have this dialogue with our code

Developer: "Hey, I see that the function showGreeting() returns some fun text."

Computer: "Yup, it sure does! Try it out! Just give me a value and I'll put in inside of the sentence."

Developer: "Okay, but first I need to do a couple of steps to assemble the data for you."

Computer: "Oh sure! Take your time. Just remember to make it an object, that has the property of name. But do what you must."

How Callbacks Can Affect the Program Thread

We talked in the previous module about how our Program thread reads each line of code, then runs that line of code before moving on to the next.

But what happens if our call back is retrieving some data and it's taking a bit too long? Our thread is at mercy of that long process.

That is something we need to consider when we are using callbacks.

For an example of what this might look like, let's look at our code from above. This time, however, we will add in this synchronous action (the for loop) and see what gets printed first:

function callbackFunction(){
    for(let i = 0; i < 100; i++){
        console.log(i)
    }

     const data = {
        name: 'Ralf Machio', 
        age: 66, 
        occupation: 'kickboxing'
    }
    return data;
}

function showData(dataFromFunction){
    return "hello " + dataFromFunction.name
}

console.log(
    showData(callbackFunction())
)

We see after we run the code, it shows

98
99
hello Ralf Machio

The code has to wait until the callback function is finished to continue doing what it was intending to do.

We will continue in the next section with Promises and see how they can be use optimize our code base.

PreviousIntroNextPromises

Last updated 7 years ago

To refer back to the image form our last section, here is what the program thread looks like:

Sync