Async JS Crash Course – Callbacks, Promises, Async Await
- December 24, 2023
- Posted by: MainInstructor
- Category: Go JavaScript React
![*](https://i0.wp.com/allprowebdesigns.com/wp-content/uploads/2023/12/1703412107_maxresdefault.jpg?resize=840%2C430&ssl=1)
Video Title: Async JS Crash Course – Callbacks, Promises, Async Await
Hey what’s going on guys so this is gonna be a crash course in asynchronous JavaScript so we’re basically going to cover a couple different things I want to cover callbacks promises and also the asynch of weight syntax now these are all ways to deal with asynchronous data and what that means basically
Synchronous is when something’s going on but you don’t want to wait until that thing is done to continue your program you want to continue while it’s happening so what’s happening asynchronously rather than synchronous programming where something happens and you wait until it’s completely finished until you move on to the next now
Asynchronous programming is is very relevant to JavaScript because we’re often making requests to servers elsewhere and it can take a couple seconds to get your data back for instance and you might not want your program to stall and wait for that data to come back you want to keep going and
And keep doing something so this is where callbacks come in and callbacks were used for a long time until es6 was released or es2015 where promises were introduced to the language and promises give you a more elegant way to handle asynchronous data and then in I think it
Was es7 async await was introduced which is still dealing with promises just in a different way you’re dealing with the response in a way that’s a little more elegant and it looks it looks more like synchronous programming rather than using the dot then and so on if you guys
Have ever used promises so we’re going to cover all those things initially I wanted to do I was going to do a separate video on them all but I figured they’re all relevant we’re actually going to use some of the same code and the callbacks and promises you can see
What you have to do to basically change it from a callback to a promise we’re also going to take a look at promise dot all where if you are resolving multiple promises you can do that you know call them all at the same time and wait for each one to beat
And a lot of this code is actually from my modern JavaScript from the beginning course on udemy so if you’re interested in 21 and a half our course on just vanilla JavaScript just core concepts building some projects check that course I’ll put a link in the description
Alright so let’s get started here I just have an index.html file I have a callback CAS and it promises dot J s and we’re gonna start with callbacks and you can see I just have look this should actually be callbacks down here alright so let’s go over to callbacks j s and
What we’re gonna do is we’re gonna kind of mimic Pope blogposts on a server and getting them and then creating a blog post so we’re just gonna have an array and call it posts and we’ll have an array of two posts these are just gonna be objects so title post one and body
I’ll say this is post one and let’s copy this down and then we’ll have one more post so this will be post two and I realize that a lot of you guys might already know this stuff but you know I like to create you know beginner to intermediate videos on my channel so
People just learning this stuff you know it’s R it’s really important and I mean there’s not in my opinion there’s not a lot of great resources out there to learn this type of stuff at least videos you know there’s a lot of documentation but a lot of people don’t like reading
Documentation so what we want to do here is create a function called get posts okay now remember we’re mimicking how how it is to fetch from a server and that could take a couple seconds or whatever so we’re gonna use set timeout here okay set timeout is
Just it takes in a callback function so we could put a function in here and then it takes in a certain amount of time where you want to delay whatever you put in here so I’m going to delay it by a sec so we want 1,000 which is 1,000
Milliseconds now you can use this syntax or you can use an arrow function which is what I’m gonna do so I’m going to remove the word function and just put in an arrow like that okay we’ll keep this es6 style so inside this set timeout I’m
Going to the purpose of this is to get these posts here and then put them on the page so let’s do let’s create a variable called output we’re just going to initialize it to nothing and then we want to loop through the posts so you
Could use like a for loop here if you want but I’m going to use the high order for each method so I’m going to say posts posts dot for each and then this actually takes in a callback as well you could put function in here but I’m just
Gonna use an arrow function and then as far as a parameter goes I’m gonna say post this could be anything but I’m gonna call it post because that’s what it is he can also use passing an index if you want and then for each post we want to
Add it to the output variables so let’s say output and we want to append so I’m gonna say plus equals we’ll use some backticks here so that we can use template syntax our template literal whatever it is and then we’re going to just put in a lies here and I want the
Post title so I’m going to use this syntax so I can you put a variable in we’ll take that post which comes from this right here so basically we’re iterating through here and then we can grab the title or the body so I’m just gonna grab the
Title so post title and then right after the for each not within it but right after it sorry about that guys sorry about that so right after the for each we want to just insert it into the body so I’m going to say document body dot in our HTML does
Really matter how we how we insert it here and we’re gonna set that equal to the output okay so we need to actually call this function for it to work so we’ll say get posts and let’s save and then what happens is after a second remember it’s in a set timeout for a
Second it’s gonna load the two posts okay it did great we get it here the posts from the array and then we’re looping through and then we’re outputting them or we’re putting them into the output variable and then outputting that on to the page with this line
Alright so pretty easy now let’s create another function called create post okay and this is going to take in a new post that we pass in and we want to do a set timeout here as well because remember we’re we’re hypothetically dealing with a server so let’s say set timeout we’ll
Put an arrow function here and let’s say this one takes two seconds so 2,000 milliseconds and inside here all I want to do is take posts and I want to push on to the post array the new post like that so what what do we want to happen
We want to get the post and then we want to create a new one that’s it right so let’s do it let’s say create post and let’s pass in an object here with a title and we’ll just call it post three and the body will say this is post three
Okay simple we get the post then we create the post save wait a minute unexpected token one oh I forgot the function all right so there we go post one post two where is post three now the reason that we’re not seeing post three is because the create post
Took longer than the get post the get post happened in one second okay our server returned it in one second the create post however took two seconds but by the time we ran this create post this it was the dom was already painted okay so we can’t do anything beyond that point
So this is where asynchronous programming comes in and this is where callbacks come in which is one way to handle it so let’s do that let’s let’s actually make this work by using a callback so this create post here what we would do is we would actually have this take
In a function and we’ll use we’ll call it callback because you could essentially call this anything but this is common practice and then we want that function to be called right after that post is pushed on okay so right here will say callback like that and then all
We have to do is now make this get post this callback so that it runs right after this is pushed not waiting two seconds for the entire function so we can completely get rid of that and then add in the next second parameter of get post like that okay no parenthesis and
Let’s save and see what happens okay so what happened is it waited two seconds and then it showed all of the posts and the reason it waited is because it had to wait to create the post before it actually called the callback okay so it
Had to push on to it and then call a callback and this whole thing took two seconds but it adds the extra post okay so this is a good example of how callbacks work and why you would use a callback so let’s now look at promises okay and I’m gonna basically use the
Same code or start with the same code so we don’t need the actual call here so let’s grab the posts and the two functions and let’s put them into promises all right and let’s change in index.html we’ll change this to promises dot J s okay now the get posts
We’re just going to leave okay we can leave that but for create posts what we want to do is instead of passing in a callback we don’t want to do that and we don’t want to run the callback instead we want to return a promise so to do that we want
To simply return a new promise and then a promise takes in a callback I’m going to use an arrow function and it takes in two parameters okay so it takes in resolve and reject so basically when you want to resolve a promise successfully you call resolve when something goes
Wrong if you have some kind of error you want to call reject so we want to do the same functionality here that we did we just want to put this inside the new promise like that and to resolve actually what I’m going to do is just create a variable called error and I’m
Gonna set it to false normally this would you do some kind of error checking you don’t have to but if you wanted to you would do some kind of error checking and let’s see if that is not true so if no error then we simply want to resolve when I resolve our
Promise else then we want to reject and we want to send a message we’ll just say error something went wrong okay and that’s it so let’s go down here and let’s call create post let’s pass in our put our actual post so we’ll say title post three
And body will say this whoops this is post three can’t type okay now we’re not going to pass in a callback like get post so we’re not doing that anymore we’re this returns a promise meaning that we can now use the dot then syntax
So we can say dot then and then in here we want to pass in get posts like that all right so let’s try and run it so we’ll save and there we go so basically it’s waiting it’s gonna it’s setting the timeout and then as soon as it’s done
It’s gonna resolve once it resolves then it’ll call get posts okay now if we wanted an error message like let’s set error to true so since air is set to true it’s going to reject now if I save this and run it we get an uncaught
Promise okay or an uncaught error so the solution for this and you guys probably use this before is dot catch so under the dot then we want to do dot catch and pass in error and then let’s just console dot log the error and save and
Now you see that we get whoops I spelt that wrong something went wrong yeah I can’t spell that’s a winner wrong but now you can see that we’re actually getting a nice clean error rather than just an uncaught promise or whatever in in for the most part in my experience
You’re mostly going to be dealing with promises so for instance when you use the fetch API or Axios or anything that uses promises the Mongoose library for DB for nodejs uses promises you know more and more libraries are using promises now so you’re mostly going to be dealing with
The response rather than creating them yourselves but you should also know how to create them yourself which is just basically new promise so what I want to do now is look at promise dot all because if you have a lot of different promises you don’t want it you don’t
Want to keep having dot then dot then dot then so you can use to promise dot all in that case so I’m gonna comment out this call and let’s go down here let’s actually change the error back to false to and let’s look at promise okay
So let’s just create a bunch of promises will say cons promise 1 equals new actually we can just simply do promise dot resolve okay as long as we resolve it and we’ll just say hello world and then we could say promise to we could just set this to a variable like 10 if
We wanted to and then just give me different examples we could say new whoops promise 3 equals new promise and we could pass in function with resolve reject and let’s set that to let’s do a set timeout and we’ll call resolve and let’s call that in two thousand milliseconds and
We’ll just pass in goodbye okay so now what we can do is we can call promise dot all and what this does is it takes in an array of promises so we have three of these up here let’s say Promised One let’s do promise to and promise three
And then this will take a dot then so we want to do a dot then and pass in here or a callback so we’ll use an arrow function and it will take in values like that and then let’s just console.log so we don’t need that let’s console dot log values all right
Let’s see what happens if I save this alright so what happened is it gave us back an array with the hello world so the first promise the second which is just a number and then this one goodbye which we actually set a timeout of two thousand or two seconds and that’s why
It took two seconds to actually return everything it’s gonna take however long the longest promise is that’s how long it’s going to take to actually do to actually show us the values all right and just to add one more thing in here let’s say Const
Promise for now well I’m sure a lot of you guys have worked with the fetch API to make Ajax calls or to make HTTP requests I should say which returns a promise so let’s fetch from let’s see let’s use the Jason type a code or jate what is it
It’s Jason placeholder dot type echo calm and we can make a request to let’s say the users right here and get users I’m gonna grab that URL and pass it in here now this returns a promise now fetch is a little weird because what
Happens is it is you need to do two dot bends when you use fetch because you first need to format it usually to Jason and then the next dot then will actually give you the data so if I keep it as is and I pass in promise for and save it’s
Gonna work but let’s if we look at the response here we just get like this weird stuff what we want to do is for fetch we want to do dot then and we want to map the response to res dot Jason like that and now if we run it it should
Give us the actual data which you can see right here is gonna be ten users all right so that’s promise not all pretty easy now let’s look at let’s see let’s look at a sink await okay so I’m going to comment this out and we don’t want to
Change any of this stuff I mean a sink await it’s a way to handle responses it’s not like a different way to write them or anything basically we need to have a function that’s labeled asynchronous so let’s go down here actually we’ll go above this because
This promise dot all has nothing to do with the code above it let’s say a sink oh wait alright so what we want to do is create a function and I’m just going to call it an it now this function has to be labeled async if we want to use a
Weight inside of it and a weight does just that it waits for an a synchronous process or action to complete so what we’ll do is we’ll call create posts okay so I’m just going to copy this here without the dot then just simply the create posts with the the title and the
Body passed in except we want to call right before it a weight okay and then after that we can just simply call get posts so we’re waiting for this to be done until we move on and call this so now we just need to call an
It and let’s save and we should see them pop up on the screen and there we go alright so that’s how a sync away it works it’s just a more elegant way to to handle promises now if we wanted to use it like let’s say with fetch we could do
That as well so I’ll go ahead and comment that out let’s go out here let’s say a sync oh wait with fetch okay so let’s copy what we did here just grab that and we’re gonna need an async function let’s just call this we’ll say function fetch data or fetch users and
Then we want to call that fetch except we want to put this into a variable and let’s call it response or res and set it to a wait fetch because remember this returns a promise now again the fetch API is a little weird because the first promise
It returns is gonna its we’re gonna need to call res dot Jason on that so what we would do is create another variable called data and set it to a weight and then res dot jason like that and then we could console dot log the data so let’s
Save that and it’s not gonna do anything because we didn’t call it so let’s call fetch users and save and there we go so we should get 10 users ok so it’s just a cleaner way of dealing with promises instead of doing the dot then and all that stuff especially with fetch
Makes it look even nicer we just have these variables and everything is just one after another there’s no dot then or dot you know whatever and it’s it’s cleaner than callbacks as well so I mean that’s pretty much it guys I wanted to just cover the basics and kind of you
Know for those of you that that weren’t really wrapping your head around this stuff and I know a lot of you already know this and that’s fine you know a refresher never hurts but that’s gonna be it guys so I am working on some longer form content some projects some
View J s view X stuff some react stuff some some Django laravel so stay tuned for that is just taking me a little while to get to get some stuff together and to get some some dealings in order in my personal life and you know if you
Guys watched my last video tells you a little bit of what’s going on but thanks for watching hopefully you like this if you did please leave it a like and I will see you in the next video
-
Sale!
Wireless WIFI Repeater Extender Amplifier Booster 300Mbps
$29.99$14.99 Add to cartWireless WIFI Repeater Extender Amplifier Booster 300Mbps
Categories: Electronics, Wi-Fi Router, Wireless Wi-Fi Extender Tags: 300Mbps, 802.11N, Amplifier, Booster, Extender, mobile wi-fi booster, Remote, WIFI, Wireless, Wireless WIFI, Wireless WIFI Repeater, Wireless WIFI Repeater Extender, Wireless WIFI Repeater Extender Amplifier, Wireless WIFI Repeater Extender Amplifier Booster, Wireless WIFI Repeater Extender Amplifier Booster 300Mbps$29.99$14.99 -
Sale!
Full RGB Light Design Gaming Headset Headphones with Mic
$24.99$14.99 Add to cartFull RGB Light Design Gaming Headset Headphones with Mic
Categories: Electronics, Gaming, Gaming Headsets Tags: Design, Full, Full RGB Light Design Gaming Headset, Full RGB Light Design Gaming Headset Headphones, Full RGB Light Design Gaming Headset Headphones with Mic, Gamer, Gaming, Gaming Headset Headphones, gaming headset wireless, Headphone, Headphones, Headset, Light, Mic, Package, RGB$24.99$14.99 -
Sale!
Wireless BlueTooth Multi-Device Keyboard Mouse Combo
$39.99$19.99 Add to cartWireless BlueTooth Multi-Device Keyboard Mouse Combo
Categories: Electronics, Gaming, Gaming Keyboards, Keyboard Mouse Combos Tags: Combo, Keyboard, keyboard mouse combos, Mouse, MultiDevice, Set, WireKeyboard Mouse Combo, Wireless, Wireless BlueTooth Keyboard Mouse Combo, Wireless BlueTooth Keyboard Mouse Combos, Wireless BlueTooth Multi-Device Keyboard Mouse Combo, Wireless BlueTooth Multi-Device Keyboard Mouse Combos$39.99$19.99 -
Sale!
High Back Leather Executive Adjustable Swivel Gaming Chair with Headrest and Lumbar
$199.99$139.99 Add to cartHigh Back Leather Executive Adjustable Swivel Gaming Chair with Headrest and Lumbar
Categories: Gaming, Gaming Chairs Tags: Adjustable, Chair, computer chairs, Desk, Executive, Gaming, Girl, Headrest, High, High Back Leather Executive Adjustable Swivel Gaming Chair, High Back Leather Executive Adjustable Swivel Gaming Chair with Headrest, High Back Leather Executive Adjustable Swivel Gaming Chair with Headrest and Lumbar, High Back Leather Executive Adjustable Swivel Gaming Chairs, Leather, Lumbar, Office, Racing, Swivel$199.99$139.99 -
Sale!
Professional LED Light Wired Gaming Headphones with Noise Cancelling Microphone
$29.99$19.99 Select optionsProfessional LED Light Wired Gaming Headphones with Noise Cancelling Microphone
SKU: N/A Categories: Electronics, Gaming, Gaming Headsets Tags: Cancelling, Gaming, Gaming Headphones with Noise Cancelling Microphone, gaming headset, Headphones, Headset, LED, Light, Mic, Microphone, Noise, Professional, Professional LED Light Wired Gaming Headphones, Professional LED Light Wired Gaming Headphones with Noise Cancelling Microphone, Wired, Wired Gaming Headphones, Wired Gaming Headphones with Noise Cancelling Microphone$29.99$19.99 -
Sale!
Gaming Desk with LED Lights USB Power Outlets and Charging Ports
$349.99$249.99 Select optionsGaming Desk with LED Lights USB Power Outlets and Charging Ports
SKU: N/A Categories: Computer Desk, Gaming, Gaming Desk Tags: and Charging Ports, Charging, Desk, Desks, Gaming, gaming desk with led lights, Gaming Desks with LED Lights, Home, LED, Lights, Monitor, Office, Outlets, Port, Power, Room, Stand, USB, USB Power Outlets, White, Workstation$349.99$249.99 -
Sale!
Wired Mixed Backlit Anti-Ghosting Gaming Keyboard
$99.99$79.99 Add to cartWired Mixed Backlit Anti-Ghosting Gaming Keyboard
Categories: Electronics, Gaming, Gaming Keyboards Tags: Antighosting, Backlit, Blue, brown, Gaming, Gaming Keyboard, gaming keyboards, gaming keyboards and mouse, Keyboard, Laptop, Switch, Wired, Wired Mixed Backlit Anti-Ghosting Gaming Keyboard, Wired Mixed Backlit Anti-Ghosting Gaming Keyboards, Wired Mixed Backlit Gaming Keyboard$99.99$79.99 -
Sale!
Wireless Bluetooth 5.3 ANC Noise Cancellation Hi-Res Over the Ear Headphones Headset
$119.99$59.99 Add to cartWireless Bluetooth 5.3 ANC Noise Cancellation Hi-Res Over the Ear Headphones Headset
Categories: Electronics, Gaming, Gaming Headsets Tags: 5.3 ANC Noise Cancellation Hi-Res Over the Ear Headphones Headset, ANC, Audio, Bluetooth, Cancellation, Ear, Earphone, gaming headset, Headphones, Headset, Hi-Res Over the Ear Headphones Headset, HiRes, Noise, Wireless, Wireless Bluetooth 5.3 ANC Noise Cancellation Hi-Res Headphones, Wireless Bluetooth 5.3 ANC Noise Cancellation Hi-Res Over the Ear Headphones Headset, Wireless Bluetooth 5.3 ANC Noise Cancellation Hi-Res Over the Ear Headphones Headsets$119.99$59.99 -
Sale!
Wired Sports Gaming Headset Earbuds with Microphone
$19.99$9.99 Select optionsWired Sports Gaming Headset Earbuds with Microphone
SKU: N/A Categories: Gaming, Gaming Headsets Tags: Accessories, Earbud, Earphone, Earphones, Gaming, gaming headset with microphone, Headphones, Headset, IOS, Microphone, Sports, Wired, Wired Sports Gaming Headset Earbuds, Wired Sports Gaming Headset Earbuds with Microphone, Wired Sports Headset Earbuds$19.99$9.99 -
Sale!
150W Universal Multi USB Fast Charger 16 Port MAX Charging Station
$49.99$29.99 Add to cart150W Universal Multi USB Fast Charger 16 Port MAX Charging Station
Categories: Charging Stations, Electronics Tags: 150W, 150W Charging Station, 150W Universal Multi USB Charging Station, 150W Universal Multi USB Fast Charger 16 Port MAX Charging Station, 150W Universal Multi USB Fast Charger 16 Port MAX Charging Stations, 150W Universal Multi USB MAX Charging Station, 16 Port MAX Charging Station, 3.5A, Charger, Charging, Fast, laptop charging stations, Max, Multi, Port, Stand, Station, Universal, USB$49.99$29.99
This has definitely increased my comfort level with these topics by a good magnitude, thanks for that.. 👍
very comprehensible, thank you
async
apt
select
Hands down the best video on async.
Simple and effective.
nice explaination sir………….
22:54 is it necessary to use the await before the res.json()?
Not all heros wear capes! Thank you!
Great video, thanks!
This was amazing 🙂 Thank you!
Thanks from Ukraine!
This is the best explanation of this concept on the web…. this along with the 5 part under the hood series has FINALLY put the pieces together on how to finally DESIGN a structure of my app (coming from C/Delphi this is a wild new world)
This is absolutely great… This is gold, thank you Sir.
Very well explained, loved the simplicity of the example in which you also included an API call which will be the most common usecase for promises , the transition from callbacks to promises, to the transition to Promise.all(), to the transition to Async/Await.
10+/10.
That helped, thanks!
great lecture
awsome thanks
the best async explanation on youtube!!!
So async is just running things at the same time
Not bad, but it didn't make sense to me why functions starting with 'await' return with Promise. I'm a beginner in js, and I've been up for 2 days trying to figure out how to wait 1 second in each loop within a for loop, and thus check with document.evaluate() whether something has appeared in the DOM. I return in vain with bool from the await function, because it seems to return a Promise<bool> type, which is always truthy, and that's not what I actually need… I want the code to check if a given element is rendered within the given timeout.
why we have to call the callback inside timeout, whynot outside the timeout function
When you say high order forEach loop instead of a for loop what do you mean by “high order”? Thanks!
Thank you it was a great video I needed that
Thank you for this.
Beautiful. Your example in 8:30 was just what I needed to understand this concept of Async/callbacks. I have been watching many classes on youtube about this stuff and yours was the only one I could understand seamlessly, thanks!
the best explanation
I learned php from you many years ago when you had a crash course with stuff like chat, blog,… Now I'm still learning from you after so many years!
Thank you Brad Traversy!
Thank you for making my journey easier sir!
Loved it. I'm glad you went from ground up because this has been an issue living inside my head rent free.
Valuable content
Plunker link doesn't work anymore 🙁
Only thing that is missing – how catch error in last scenario with async and await
Watching it for 3rd time 😅
great explanation
you're such a legend
the code link is not working please fix it
Hello and thank you.🙂
Does anyone have the code from the lesson (the link to the code in the description is not working(plnkr))
Nice, simple explanation. I love it 🙂