Asynchronous JavaScript Tutorial #4 - Callback Functions

Net Ninja · Beginner ·🌐 Frontend Engineering ·5y ago

Key Takeaways

Explains asynchronous JavaScript using callback functions, demonstrating reusable code and request handling

Full Transcript

okay then so far we're making this request and then we're reacting when we get some kind of data back or if there's an error now it would be nice if we could wrap up all of this code inside a function called get to do's for example so that we could call this function whenever we want to run this code and make a request that makes it more reusable so let's do that first of all come to the top and create a new constant we'll call this get to do's that's the function name and set it equal to a new arrow function like so now inside this function that's where we want to do all of this request of so cut that and paste it inside here just scoot this in a little bit all right then so now we have all of this request stored inside a function and if i want to run this code now all i have to do is come down here and say get to do's like so so if i save this then everything's still going to work the same way but the good thing is now we're making this more reusable so i could call this multiple times if i wanted to now i don't want to at the minute but the option is there if i did now at the minute every time we call this to-do's function if i did call this multiple times all we're doing each time is just logging the response to the console now it would be nice if i could instead pass in a callback function to get to do's which we then fire over here so we could specify how we want to react in that callback function then every time we call get to do's we could specify a different kind of callback function to do something different each time if we wanted to instead of just always doing this inside the function so that's what i'm going to show you how to do the first thing we're going to do is specify a callback function in here as an argument to get to do's so that will be just an empty arrow function at the minute now obviously since we're passing this through as an argument we take it inside the function as a parameter i'm just going to call this callback but you can call it what you want now when we have either some kind of successful response or a bad response we can instead of logging this to the console just called the callback so i'm just going to say over here instead of this like so and i'm going to do exactly the same thing down here callback now whenever it reaches ready state 4 this request and we get a status of 200 we call the callback or even if we don't get a status of 200 and we just reached ready state 4 we still do that callback so this function right here is going to fire because we're invoking it over here and we pass it in up here so let's just test this i'm going to console.log and i'm going to say callback fired so save this and refresh we can see now callback is fired now the problem is even if we have an error over here and save we still just get callback fired we see the error but it's still firing this and we're getting the same kind of action even though we've got an error and that's because all we're doing in both cases over here even if it's a success we have data we're calling callback and when we don't have a success but it finishes the request we're still just firing callback now it would be nice instead if we could pass through the data here and the error here so then we can check for that inside the callback down here so what we're going to do is take in two parameters into this callback function we're going to take in an error and we're going to take in data now convention is when we do callbacks like this from a network request we always do the error first then the data second that's just convention so up here what we could do is pass through some of these values now obviously in this case if the status is 200 we don't have an error and all we have is the response text the data so for the first parameter right here error and for the first argument up here to match it we can pass through undefined because obviously the error in this case is going to be undefined now the second parameter is the response text so let's say request dot response text and now we're passing the data through as the second parameter okay so down here instead of doing undefined for the first argument we're going to say could not fetch data so that is the error right here so we're passing that through as the error argument or the error parameter here now the second one obviously is going to be undefined because in this case we don't have data because we don't have a status of 200. so now if we were to save this and run it then we're calling the callback function slightly differently each time if there's an error we call it with this error and undefined for the data if it's a success then we're calling it with undefined for the error and this data so let me just do this with a success first of all and what i'm going to do in each case down here is console.log error and data now we're doing it to the correct endpoint first so this should run so we can see if we scroll up now that we now get callback fired then we get undefined for the error and then this for the data now if we switch this up so that this is incorrect save it now we get carbot fired this for the error could not fetch data and undefined for the data itself okay so now what we could do in here is check if we have an error then do one thing if we don't have an error we can do another so let's say if and then error like that if there is an error remember this string over here is going to be truthy if there's not an error this is going to be false so this is only going to fire if we fire the callback function this way so what i'm going to do right here is console.log the error and i'm going to do an else case right here and say console.log data like that so let's try this out currently we should get the error right here because this is incorrect save it and we can see callback fired could not fetch data if we change this so it is correct like that and save it now we see we get the data and at the top it says call backfired so this is all working now we've made our code more reusable by putting it inside a get to this function then we can call that function to go and get the to do's passing a callback function as an argument we take that as a parameter and then we fire it down here with either the error or the data if it's a success or not so that is a lot more reusable and we could call get to do's as many times as we want so i could copy that and paste it down here and each time around we could do something different in the callback function so it's more flexible so i want to tie this into the whole idea of asynchronous code right now because remember that's what this chapter is all about asynchronous code and i said that asynchronous code is something that can start now and finish later so let's put this into practice i'm just going to say console.log up here 1 and then i'm gonna duplicate that and in fact i'm gonna copy it and paste it down here a couple of times as well we'll change this to two this to three and this to four so we'll save that and now what should happen is this should fire this should fire then this should start that's going to start the network request it's going to pass this off to another part of the browser so that we can carry on with these statements in the queue and we'll carry on with console log three then four then at the end we're going to fire this callback function when the data has come back to us and the rest of the statements have been fired so this is not going to be blocking code so if i save that we can see over here if i scroll to the top we get one two three four then at the end we get callback fired and the data once the network request has completed we're not having to wait over here for this to complete before we fire these two things it's non-blocking code it's asynchronous code meaning it starts now and can finish later so this whole idea of starting something right away but finishing it later and letting the rest of the code run in the meantime is the beating heart of asynchronous behavior

Original Description

Hey gang, in this async javascript tutorial we'll take a look at callback functions and how they work. Get the full Modern JavaScript tutorial on Udemy here (discount auto-applied): https://www.thenetninja.co.uk/udemy/modern-javascript 🐱‍👤🐱‍👤 JOIN THE GANG - https://www.youtube.com/channel/UCW5YeuERMmlnqo4oq8vwUpg/join ---------------------------------------- 🐱‍💻 🐱‍💻 My Udemy Courses: + Modern JavaScript - https://www.thenetninja.co.uk/udemy/modern-javascript + Vue JS & Firebase - http://www.thenetninja.co.uk/udemy/vue-and-firebase + D3.js & Firebase - https://www.thenetninja.co.uk/udemy/d3-and-firebase 🐱‍💻 🐱‍💻 Helpful Links: + Get VS Code - https://code.visualstudio.com/ 🐱‍💻 🐱‍💻 Social Links: Facebook - https://www.facebook.com/thenetninjauk Twitter - https://twitter.com/thenetninjauk Instagram - https://www.instagram.com/thenetninja/
Watch on YouTube ↗ (saves to browser)
Sign in to unlock AI tutor explanation · ⚡30

Playlist

Uploads from Net Ninja · Net Ninja · 0 of 60

← Previous Next →
1 Regular Expressions (RegEx) Tutorial #14 - Matching a Username
Regular Expressions (RegEx) Tutorial #14 - Matching a Username
Net Ninja
2 Regular Expressions (RegEx) Tutorial #15 - Email RegEx Pattern
Regular Expressions (RegEx) Tutorial #15 - Email RegEx Pattern
Net Ninja
3 Regular Expressions (RegEx) Tutorial #16 - Finishing Touches
Regular Expressions (RegEx) Tutorial #16 - Finishing Touches
Net Ninja
4 GraphQL Tutorial #1 - Introduction to GraphQL
GraphQL Tutorial #1 - Introduction to GraphQL
Net Ninja
5 GraphQL Tutorial #2 - A Birdseye View of GraphQL
GraphQL Tutorial #2 - A Birdseye View of GraphQL
Net Ninja
6 GraphQL Tutorial #3 - Project (stack) Overview
GraphQL Tutorial #3 - Project (stack) Overview
Net Ninja
7 GraphQL Tutorial #4 - Making Queries (front-end preview)
GraphQL Tutorial #4 - Making Queries (front-end preview)
Net Ninja
8 GraphQL Tutorial #5 - Express App Setup
GraphQL Tutorial #5 - Express App Setup
Net Ninja
9 GraphQL Tutorial #6 - Setting up GraphQL
GraphQL Tutorial #6 - Setting up GraphQL
Net Ninja
10 GraphQL Tutorial #7 - GraphQL Schema
GraphQL Tutorial #7 - GraphQL Schema
Net Ninja
11 GraphQL Tutorial #8 - Root Query
GraphQL Tutorial #8 - Root Query
Net Ninja
12 GraphQL Tutorial #9 - The Resolve Function
GraphQL Tutorial #9 - The Resolve Function
Net Ninja
13 GraphQL Tutorial #10 - Testing Queries in Graphiql
GraphQL Tutorial #10 - Testing Queries in Graphiql
Net Ninja
14 GraphQL Tutorial #11 - GraphQL ID Type
GraphQL Tutorial #11 - GraphQL ID Type
Net Ninja
15 GraphQL Tutorial #12 - Author Type
GraphQL Tutorial #12 - Author Type
Net Ninja
16 GraphQL Tutorial #13 - Type Relations
GraphQL Tutorial #13 - Type Relations
Net Ninja
17 GraphQL Tutorial #14 - GraphQL Lists
GraphQL Tutorial #14 - GraphQL Lists
Net Ninja
18 GraphQL Tutorial #15 - More on Root Queries
GraphQL Tutorial #15 - More on Root Queries
Net Ninja
19 GraphQL Tutorial #16 - Connecting to mLab
GraphQL Tutorial #16 - Connecting to mLab
Net Ninja
20 GraphQL Tutorial #17 - Mongoose Models
GraphQL Tutorial #17 - Mongoose Models
Net Ninja
21 GraphQL Tutorial #18 - Mutations
GraphQL Tutorial #18 - Mutations
Net Ninja
22 GraphQL Tutorial #19 - More on Mutations
GraphQL Tutorial #19 - More on Mutations
Net Ninja
23 GraphQL Tutorial #20 - Updating the Resolve Functions
GraphQL Tutorial #20 - Updating the Resolve Functions
Net Ninja
24 GraphQL Tutorial #21 - GraphQL NonNull
GraphQL Tutorial #21 - GraphQL NonNull
Net Ninja
25 GraphQL Tutorial #22 - Adding a Front-end
GraphQL Tutorial #22 - Adding a Front-end
Net Ninja
26 GraphQL Tutorial #23 - Create React App
GraphQL Tutorial #23 - Create React App
Net Ninja
27 GraphQL Tutorial #24 - Book List Component
GraphQL Tutorial #24 - Book List Component
Net Ninja
28 GraphQL Tutorial #25 - Apollo Client Setup
GraphQL Tutorial #25 - Apollo Client Setup
Net Ninja
29 GraphQL Tutorial #26 - Making Queries from React
GraphQL Tutorial #26 - Making Queries from React
Net Ninja
30 GraphQL Tutorial #27 - Rendering Data in a Component
GraphQL Tutorial #27 - Rendering Data in a Component
Net Ninja
31 GraphQL Tutorial #28 - Add Book Component
GraphQL Tutorial #28 - Add Book Component
Net Ninja
32 GraphQL Tutorial #29 - External Query File
GraphQL Tutorial #29 - External Query File
Net Ninja
33 GraphQL Tutorial #30 - Updating Component State
GraphQL Tutorial #30 - Updating Component State
Net Ninja
34 GraphQL Tutorial #31 - Composing Queries
GraphQL Tutorial #31 - Composing Queries
Net Ninja
35 GraphQL Tutorial #32 - query variables
GraphQL Tutorial #32 - query variables
Net Ninja
36 GraphQL Tutorial #33 - Re-fetching Queries
GraphQL Tutorial #33 - Re-fetching Queries
Net Ninja
37 GraphQL Tutorial #34 - Book Details Component
GraphQL Tutorial #34 - Book Details Component
Net Ninja
38 GraphQL Tutorial #36 - Styling the App
GraphQL Tutorial #36 - Styling the App
Net Ninja
39 GraphQL Tutorial #35 - Making a Single Query
GraphQL Tutorial #35 - Making a Single Query
Net Ninja
40 Build Apps with Vue & Firebase - Udemy Course
Build Apps with Vue & Firebase - Udemy Course
Net Ninja
41 Updated Vue & Firebase Course (Udemy)
Updated Vue & Firebase Course (Udemy)
Net Ninja
42 Vue & Firebase Real-time Chat (Preview) #1 - Intro
Vue & Firebase Real-time Chat (Preview) #1 - Intro
Net Ninja
43 Vue & Firebase Real-time Chat (Preview) #2 - Project Structure
Vue & Firebase Real-time Chat (Preview) #2 - Project Structure
Net Ninja
44 Vue & Firebase Real-time Chat (Preview) #3 - Firestore Setup
Vue & Firebase Real-time Chat (Preview) #3 - Firestore Setup
Net Ninja
45 Vue & Firebase Real-time Chat (Preview) #4 - Welcome Screen
Vue & Firebase Real-time Chat (Preview) #4 - Welcome Screen
Net Ninja
46 Vue & Firebase Real-time Chat (Preview) #5 - Props in Routes
Vue & Firebase Real-time Chat (Preview) #5 - Props in Routes
Net Ninja
47 Vue & Firebase Real-time Chat (Preview) #6 - Route Guards
Vue & Firebase Real-time Chat (Preview) #6 - Route Guards
Net Ninja
48 Vue & Firebase Real-time Chat (Preview) #7 - Chat Window
Vue & Firebase Real-time Chat (Preview) #7 - Chat Window
Net Ninja
49 Vue & Firebase Real-time Chat (Preview) #8 - New Message Component
Vue & Firebase Real-time Chat (Preview) #8 - New Message Component
Net Ninja
50 Object Oriented JavaScript Tutorial #1 - Introduction
Object Oriented JavaScript Tutorial #1 - Introduction
Net Ninja
51 Object Oriented JavaScript Tutorial #2 - Object Literals
Object Oriented JavaScript Tutorial #2 - Object Literals
Net Ninja
52 Object Oriented JavaScript Tutorial #3 - Updating Properties
Object Oriented JavaScript Tutorial #3 - Updating Properties
Net Ninja
53 Object Oriented JavaScript Tutorial #4 - Classes
Object Oriented JavaScript Tutorial #4 - Classes
Net Ninja
54 Object Oriented JavaScript Tutorial #5  - Class Constructors
Object Oriented JavaScript Tutorial #5 - Class Constructors
Net Ninja
55 Object Oriented JavaScript Tutorial #6 - Class Methods
Object Oriented JavaScript Tutorial #6 - Class Methods
Net Ninja
56 Object Oriented JavaScript Tutorial #7 - Method Chaining
Object Oriented JavaScript Tutorial #7 - Method Chaining
Net Ninja
57 Object Oriented JavaScript Tutorial #8 - Class Inheritance
Object Oriented JavaScript Tutorial #8 - Class Inheritance
Net Ninja
58 Object Oriented JavaScript Tutorial #9 - Constructors (under the hood)
Object Oriented JavaScript Tutorial #9 - Constructors (under the hood)
Net Ninja
59 Object Oriented JavaScript Tutorial #10 - Prototype
Object Oriented JavaScript Tutorial #10 - Prototype
Net Ninja
60 Object Oriented JavaScript Tutorial #11 - Prototype Inheritance
Object Oriented JavaScript Tutorial #11 - Prototype Inheritance
Net Ninja

Related AI Lessons

Had my Frontend Developer interview with Capgemini (Application Developer) today, and I wanted to…
Prepare for a frontend developer interview with Capgemini by reviewing JavaScript fundamentals and practicing common interview questions
Medium · JavaScript
10 Frontend Developer Tools to Boost Productivity in 2026
Boost frontend productivity with 10 essential tools for modern web app development
Medium · Programming
10 Frontend Developer Tools to Boost Productivity in 2026
Boost frontend productivity with top 10 developer tools in 2026
Medium · JavaScript
The US Frontend Engineer Market in 2026: A Data-Driven Reality Check (and the Bias That Stops Us Seeing It)
US frontend engineer hiring demand peaked in 2022 and remains flat-depressed in 2026, contrary to common assumptions
Dev.to AI
Up next
How to Open KIT Files (CodeKit Project)
File Extension Geeks
Watch →