*NEW* AJAX - Complete Fundamentals Course - Part 9: Event Loop & Async/Await | CM Code_Zone | Skillshare

Playback Speed


1.0x


  • 0.5x
  • 0.75x
  • 1x (Normal)
  • 1.25x
  • 1.5x
  • 1.75x
  • 2x

*NEW* AJAX - Complete Fundamentals Course - Part 9: Event Loop & Async/Await

teacher avatar CM Code_Zone, !false | funny, because its true

Watch this class and thousands more

Get unlimited access to every class
Taught by industry leaders & working professionals
Topics include illustration, design, photography, and more

Watch this class and thousands more

Get unlimited access to every class
Taught by industry leaders & working professionals
Topics include illustration, design, photography, and more

Lessons in This Class

    • 1.

      Class Intro

      1:07

    • 2.

      What is the Event Loop

      9:14

    • 3.

      Macro Tasks vs Micro Tasks

      8:05

    • 4.

      Creating our own Promise

      14:10

    • 5.

      Intro to Async / Await

      1:46

    • 6.

      Async returns a Promise

      2:54

    • 7.

      Intro to the Await keyword

      2:43

    • 8.

      Example of using Async / Await

      10:42

    • 9.

      Second Example of using Async/Await

      5:21

    • 10.

      Challenge intro - improving our previous class Fetch code

      1:15

    • 11.

      Challenge solution - fetching our Image using async/await

      5:46

    • 12.

      Challenge solution - fetching our IP address using async/await

      3:43

    • 13.

      Error handling using Try and Catch

      3:49

  • --
  • Beginner level
  • Intermediate level
  • Advanced level
  • All levels

Community Generated

The level is determined by a majority opinion of students who have reviewed this class. The teacher's recommendation is shown until at least 5 student responses are collected.

15

Students

--

Project

About This Class

WELCOME TO THIS SKILLSHARE SERIES ON AJAX. 

THIS IS THE LAST CLASS

What we cover in this particular Skillshare class?

We have covered of ton of information in this entire series, but for Part 9 we're going to dig deeper into the Fetch API, by discussing the modern Async / Await keywords. 

The latest AJAX uses the power of Promises to perform asynchronous server requests.

When you use a promise, the function is paused in a non-blocking way until the promise settles (or what developers call "resolves"). If the promise resolves, you get the value back.

There is nothing wrong if you want to use vanilla promises and callback functions (wrapped within .then() statements). In previous classes you have learnt how to do this. 

But a more modern way to using promises for AJAX requests is to use async and await. Async functions are enabled by default in Chrome 55 and they're fabulous.

They allow you to write promise-based code as if it were synchronous, but without blocking the main thread.

It doesn't get much better than that!

In this class we will cover topics such as: 

  • the Event Loop
  • micro tasks vs macro tasks
  • async and await
  • Promises
  • challenges
  • error handling using Try and Catch statements
  • AND A BUNCH MORE!

Stay motivated, grab a coffee, and see you in the first lecture (hopefully).

I can't wait. 

LET'S BEGIN

--- curious about what AJAX is? Look no further ...

Welcome Skillshare students to this series about AJAX.

Understanding web development is an ongoing process. To give you a foot up, I’ve gone all out to structure an all-encompassing, yet focussed, AJAX Skillshare series which I deliver to you in a way that will benefit you the most.

My Skillshare series is distinguishable in teaching you "why" things work and not just "how" to do something mindlessly.

WHO IS MY AJAX SERIES FOR?

My Skillshare AJAX series is for everybody, from beginner and advanced coders. You won’t need to do any other classes after mine to know what AJAX is.

You do need to know a little HTML and JavaScript. If you have never heard of JavaScript, it may be beneficial for you to first do my JavaScript classes before this one, but that is not essential.

This Skillshare AJAX series can be taken alone (you don’t need to do any other Skillshare series) to achieve your goals.

WHAT IS AJAX? 

AJAX allows you to update information on your web app dynamically, without a page refresh, and facilitates all-important streaming. A fine addition to your skill set. Smart and powerful.

For example. If a user wants to rate your product “⭐⭐⭐⭐⭐”. You don't want the entire page to refresh when the user decides to give your product a star review, because of the unnecessary time it wastes, especially if your page is large. 

Another example is a chat room. For obvious reasons, you don't want the page to refresh every time a new comment or a reply is posted.

AJAX goes further than just updating data on your page without a page refresh. With AJAX, you can also stream data. Think about watching a video before the entire video has downloaded to your machine. Think about Google Maps where you only need to download data that is relevant to you. AJAX makes this all possible.

Can you begin to see how powerful AJAX is, how essential it is today?  

Knowing AJAX is crucial if you want to become a fullstack developer, as it will allow you to make server requests and listen for incoming data, asynchronously. It has been noted that AJAX can get tricky at times, and I don’t dispute this, but with correct training which includes explaining the fundamentals in a simple way, you will, like me, learn to master and love AJAX.

If you want to become a full stack web developer, you need to know about AJAX and that’s what this Skillshare series is all about.

 

WHY IS THIS SKILLSHARE SERIES ON AJAX SO IMPORTANT? 

  • Your favourite websites today use AJAX
  • Other classes teach you about third-party libraries when using AJAX (like jQuery or Axios). This Skillshare series will teach you how to use pure AJAX. No shortcuts. The real deal!
  • Making HTTP requests asynchronously is at the forefront of today’s web development. In fact, it is no longer advisable or the done thing to make HTTP requests synchronously
  • Knowing how to make a server request and listen for a response, fast, is a vital skill for any web developer to master
  • As a developer, you deal with data. This data can take many forms, but the most common is XML and JSON
  • You can use AJAX to transport HTML, images, JavaScript, XML, JSON and even plain text over the internet. My Skillshare series covers all this
  • Using AJAX saves memory usage and speed up your site. For instance, Google Maps uses AJAX, so instead of loading the entire page for every event it loads the required section that you are looking at only. How efficient isn’t that
  • AJAX makes for better user experience, no argument in that
  • Every browser today has a built-in API (or object) called the XMLHttpRequest object, or the Fetch API. These objects give browsers the ability to communicate with servers, behind the scenes. This means a page can update (not totally upload) seamlessly without blocking anything on the user interface
  • After completing this AJAX Skillshare series, you will certainly be knowledgeable, confident and the “go-to” person for making AJAX requests

 

LET ME SHARE MY AJAX KNOWLEDGE WITH YOU

Understanding how AJAX works will equip you to be an awesome fullstack programmer, relevant for today. Using AJAX effectively will allow you to update parts of your website dynamically without a page refresh, stream, and save you download time, save memory space and therefore ultimately improve user experience.

Take control through understanding and providing today’s users with the fast web experience they are coming to expect.

Mastering AJAX is challenging.

In this Skillshare series, I take a deep-dive into explaining AJAX and how it works in a clear and simple way. Why do we need AJAX? Where did it come from? Why was the newer Fetch() API introduced? Why did we have to replace the XMLHttpRequest() object? Why do we have to use the new keyword when using the XHR object? What are Promises? What are Streams? What are the different data formats that we can transfer over the internet? By understanding (really understanding) these questions, and many more in this Skillshare series, you will be able to easily build advanced websites and use the full stack process. You will be able to create dynamic sites that improve user engagement and experience.

WHERE IS AJAX USED?

  1. Form validation

It can be impractical and tedious to get validation results only after submitting a form. You can use AJAX in form validation, to give near instant real-time updates on validation.

  1. Fetching data from a database dynamically without a page refresh 

If you need to fetch data from a database and display it to your page (like a blog comment, a chat response, or user's name), then using AJAX is a necessity.

  1. Sort or Filter

If you need to fetch data from a database and display it to your page (like a blog comment, a chat response, or user's name), then using AJAX is a necessity.

  1. Votes or Rating ★★★★★

The whole site need not to be refreshed if a user votes for something or rates your product. The voting and the displaying of the results can be done most efficiently using AJAX.

  1. Chat websites

Chatting is always real time. That’s why AJAX is a must have if you are going to make a successful chatting panel in your website.

  1. Blog Comments

You can load previous comments or can post a new blog commens with AJAX, easy peasy.

  1. Captcha

To make captcha (reloading captcha basically) AJAX is also the best platform to use.

  1. Streaming data & more

AJAX is used to consume data before its fully downloaded (saving you memory space and time), and a whole bunch more!

After experiencing my “AJAX” Skillshare series, which I present in a fun way, you will be knowledgeable and confident.

 

WHAT THIS SKILLSHARE SERIES COVERS

This Skillshare series is comprehensive, covering the essential fundamentals of AJAX.

AJAX refers to how browsers make HTTP requests to servers asynchronously, listen for results, and then do something with the data when it is received. AJAX is about speed and efficiency.

You can therefore think of AJAX as the engine that handles this entire back-and-forth process between the browser and the server.

Simple enough.

The only problem is that in order to truly understand AJAX, you need to understand many other concepts, and this is one of the unique aspects of my Skillshare series and style of teaching.

Simple explanations and practical examples allow you to understand the following:

  • How to write AJAX the best way
  • What is asynchronous code and how does it differ from synchronous code
  • How to use AJAX to make asynchronous requests
  • What is the event loop in JavaScript
  • What is XML and how does it differ from JSON
  • What is the HTTP protocol and what is the HTTP/2 and HTTP/3 protocol
  • What are constructor functions
  • What is the XHR object
  • What is the new fetch() API
  • What are Promises
  • What are Streams
  • Why use Async/Await
  • URL Interface, Request Interface, Header Interface and a whole bunch more!

And yes, we will code real examples and look at how AJAX works (we use both the XMLHttpRequest object and the newer Fetch API).

Why should you learn so much about AJAX?

Because AJAX allows you to update certain parts of your webpage without a page refresh. It is used for streaming and more and today use of AJAX is essential on websites. It doesn't get better than that!

*** A comprehensive AJAX series on Skillshare ***

Successful programmers know much more than memorizing a few lines of code.

They also know the fundamentals of how the browser & server interaction works behind the scenes which allows them to be fully creative, fix problems and enhance user experiences.

This is particularly true when it comes to AJAX.

If you’re wanting to become a full stack developer, you need to know, really know, how to make an AJAX request. You need to understand how AJAX was created, why the modern Fetch API was introduced, what Streams are, how Promises work and why the Async/Await keywords were introduced, and a bunch more!

 

A UNIQUE APPROACH

This Skillshare series contains practical examples and fun challenges and quizzes.

Understanding how AJAX truly work is a vast topic. To get you up to speed, I’ve created a fun and comprehensive learning experience, embracing the content you need to know to succeed, and I deliver it to you in the best possible way to benefit you most.

And I make use of the latest and best features of JavaScript and browsers along the learning journey so you can stay ahead in your business.

You’ll learn simple, yet very powerful strategies to make server requests from a client.

By the end of this Skillshare series, you'll be able to “speak” and “walk” AJAX by gaining an understanding of how you can build it and configure your request in practical ways. We dig deeper in every class, and this Skillshare series has many bonus lectures which extend your knowledge base and test your skills with fun challenges.

This Skillshare series offers you the best fundamentals and practical skills with AJAX. It can be taken alone (you don’t need to do any other Skillshare series) to achieve your goals. You will emerge from this Skillshare series with an advanced understanding and practical experience with making HTTP requests. It will take you to the point where you will understand what method (GET or POST) to use when sending data, how to define where the data goes, how to set up an AJAX engine and how to check for errors. This is awesome knowledge. This Skillshare series will captivate you and catapult you to the next level and is an important part of your journey to become a leading Grandmaster in web development.

In this Skillshare series you’ll learn everything about AJAX. From the basics of building an AJAX engine, all the way to learning about XML and JSON, asynchronous code, protocols, constructor functions, Promises, Streams, HTTP protocols, Fetch API, the Async/Await keywords, and various APIs such as Fetch, URL Interface, Headers Interface and Request Interface and a whole bunch more!

If you want to become a full stack web developer, you need to take this Skillshare series on AJAX!

 

HOW IS THIS SKILLSHARE CLASS DIFFERENT?

A unique feature of my Skillshare series is the key detail I provide about how AJAX really works behind the scenes – a skill that every full-stack developer needs to master in order to utilize potential to improve.

I use simple and effective lessons to take you beyond starter libraries like Axios or jQuery. Libraries are helpful but are not a replacement for knowledge and once you can write your own, you will better be able to use and amend library code.

In this Skillshare series, I focus on the more fundamental aspect of AJAX. I use plain JavaScript which is the core programming language you need in order to use AJAX. Once you master using JavaScript with AJAX, then integration of a library can benefit you and may make sense.

In order to understand how AJAX works, I dive into topics such as protocols, constructor functions, asynchronous code, data format types (JSON and XML), Promises, Streams, error handling and how to use the keywords Async/Await with the Fetch API.

Practice makes perfect

Theory is theory … but there’s nothing like getting behind your computer and typing in code. That’s why we will be coding, laughing and pulling out our hair together as we code real life websites and exercises during this Skillshare series.

I love teaching and often use practical examples, which is why I start coding with you from the get-go. I will show you why the XHR object is a constructor function. I will show you the difference between JSON and XML. I will show you how to set up an XHR object, show you how to build Promises, show you what Streams are and how to use the new Fetch API. These concepts are all best learnt by coding up real examples. I can't wait. 

 

IS THIS SKILLSHARE CLASS FOR YOU?

Absolutely. If you fit in any of these categories then this Skillshare series is perfect for you:

#1: BUSY PEOPLE who want to become certified and confident in AJAX in the shortest time possible.

#2: PROGRAMMING DESIRE. You want to advance in the world of programming.

#3: FREELANCERS who want to know how successful developers build dynamic websites that can update information without a page refresh (like Twitter, Google Maps etc). 

#4: WEBSITE OWNERS who want to gain a solid understanding of how AJAX really works.

#5: AGENCIES who want to upskill their developers quickly.

#5: EVERYBODY who want to LEARN.

 

WHY START NOW?

Right this second, your competitors are learning how to become better web developers.

Web development is a blazing hot topic and not set to cool off in the future. We need the web more and more and advancements keep happening. But you have a distinct advantage. This Skillshare series offers memorable learning topics, actionable tactics and real-world examples to help you most.

Lets get started!

What do you get?

  • You become an AJAX expert
  • Q&A support.
  • Assignments to help you learn.

Hope you are as excited as I am to get started and get learning, and I can’t wait to show you how to confidently apply AJAX it to your own websites.

See you in class. 

Meet Your Teacher

Teacher Profile Image

CM Code_Zone

!false | funny, because its true

Teacher

Success takes sacrifice.

And sacrifice is something I know a lot about.

I am a self-taught developer so I understand how difficult and daunting it can be for a new comer. 

Today, I continue to code and stay on top of the latest technologies and programming languages. 

It's time to share the knowledge I've gained and to help others succeed. 

See full profile

Level: All Levels

Class Ratings

Expectations Met?
    Exceeded!
  • 0%
  • Yes
  • 0%
  • Somewhat
  • 0%
  • Not really
  • 0%

Why Join Skillshare?

Take award-winning Skillshare Original Classes

Each class has short lessons, hands-on projects

Your membership supports Skillshare teachers

Learn From Anywhere

Take classes on the go with the Skillshare app. Stream or download to watch on the plane, the subway, or wherever you learn best.

Transcripts

2. What is the Event Loop: Are you ready? I hope so. This is awesome section and Awesome glass and awesome few lectures talking about async and await. And this really is adding a modern flee to the already modern It's API. And I hate that word, but in order to understand async and await, you need a high level understanding on what the event loop is. I don't want to get into too much detail on the event loop that you need to know it exists. And it will just help solidify asynchronous requests. Or at, let me start right at the basics. We know that the browser, aka Chrome and JavaScript, for example, Node.js, they are single threaded. And because we're dealing with ajax, I'm more concerned right now about the browser and get this, everything inside a browser runs off a main thread. All browsers have a thing called a main thread. And on this main thread, loads of things happen. This is where the parties it for the browser. This is where your JavaScript code is executed. It is where the rendering happens and it's way the DOM, the Document Object Model loops. What does this mean? It means that if something on the main thread takes a long time to execute, everything else is going to be blocked. I want you to visualize this picture. They've being a main thread. On this main thread, everything happens like I mentioned, this is where the parties yet. It's not only JavaScript is executed in the main thread, it's also the updating of the DOM when a browser updates CSAs. This all happens on this main thread. To avoid certain tasks blocking everything else, the browser came up with a very good idea of spawning multiple threads away from the main thread. But of course, once these strains have done something that a page needs to care about, they need to come back to the main thread to give the browser that information and weight as the event tube foot in. Do you know? Well, it is the event loop that handles and manages this entire process. Come on, That's pretty cool, right? That is the even tube. And to drive the point home, why don't we look at code specifically. I want to look at the setTimeout function. We've seen it a few times in this course already. But let me break it down. This is how you write it out. It takes two arguments, the callback and milliseconds. But what does the sake timeout function mean? What is it doing? What it's doing? Two things. First thing is that it waits x milliseconds whenever we define. And once it's done, waiting for those milliseconds to pass is then going to execute the callback function. But let's now not treat this as an asynchronous function. Let's now pertain that the setTimeout function runs synchronously. If we executed it like asynchronous function, just like us, it would run on the main thread and this means it will pulls everything else until it's done. We don't want that to happen, right? That's very poor for user experience. How do we solve this? Well, That's right To avoid this state timeout function is not run on the main thread. Remember those side trades. A fancy development term for that is that it's being run in parallel. And that's just fancy talk for off the main thread on one of those side threads that if you really stop thinking about it, this is going to pose another problem because when it comes time to execute that callback function, remember, after the milliseconds have passed, then what happens? Well, that callback function has to be executed and way is the execution taking place. That's right on the main thread. Can you see the problem with that automatically going straight into the main thread whenever they call that function is ready. The problem is that you could be running a lot of JavaScript code in parallel. This means that potentially you could be editing the same DOM at the same time, NG day full run into what developers called race condition problems. Effectively what that means is you don't want one JavaScript function half manipulating the DOM. And then suddenly this callback function gets thrown into the main thread and starts executing another part of the DOM, or even worse, overriding what the first JavaScript execution function was doing. How do we solve this problem? Well, the browser, again, is very clever to ensure that you don't run into problems with executing multiple JavaScript code at the same time, task cues were introduced. I know what you're thinking, you're thinking client development is hard enough. Now when we're talking about event loops, we've got terms like parallel off the main thread side trades task queues, but just doesn't stop. Don't worry, don't worry. I know I've been there, but it really does make intuitive sense. If you just take a step back, you've got that main thread. Can throw everything at the main thread at the same time they fall. Functions, tasks have to be queued. So this really does make sense. Just remember, a key part of how the event loop works is the concept of task queues. And how did these task queues work? Well, what the browser does is it tells the oven tube that it has some functions at wanted to do something on the main thread. And your browser's going to add that function to the task queue when that function is ready to execute. Basically when the function is ready, it gets added to this task. You, it's waiting. And only when there's a gap in advantage people to be put back on the main thread. This ensures that things are executed in an orderly manner. It makes sense because eventually the vent loop, we'll get to executing those tasks when it's ready. Then let's talk again about our sit timeout function because we know the setTimeout function is actually an asynchronous function. How does it look in reality? Well, again, we'd write it out exactly the same way. Again, two things are happening when we execute this function. But this is what's really happening. One, we've got a weight x milliseconds, but this is being run in parallel. You know what that means? Not being run on the main thread. What's the second thing the browser does here? It will queue task when the callback is ready. Once we've waited a certain amount of milliseconds, and that callback is ready to execute. The browser will edit to the task. Of course, the event loop will invoke the callback function when it's ready. When the event loop is ready. I'm just going to blow your mind a little bit more. This is getting very advanced, or perhaps could have stopped here. But you do need to know that they're all different categories of tasks. We've got microtasks and microtasks. I guess a good way of thinking about it is you've got important tasks and not so important tasks. What does the macro task? We'll tasks in the macro task queue, like the sit timeout function. Then you have to wait for the next round of the event loop before being executed. Another way of saying it is that the tasks and the macro Q processed one item at a time. However, tasks in the micro task queue will be run in the current round of the event. Another nuance is that micro queue tasks all process to completion, including any items, any functions, and the additional code you add to the queue in real-time. And because of the high importance on microtasks, that means the event loop is going to block rendering while it's executing microtasks. Client, okay, client, I get it, I get it, but where does ajax fit into all this? Well, we know that ajax deals with promises. Promises of very, very important when it comes to browsers. This means when the code is eventually edit to the main thread to execute. Let me say this. When the browser adds those callback functions to the task queue, it treats these functions as micro tasks. I know, I know. Probably blowing your mind. Don't worry. You don't strictly need to know about all of this in order to understand ajax. But it's very, very interesting and advanced concepts. It's fun. And I want you to be a grandmaster. In the next few lectures, I want us to now hop to the console and I want to start looking at how the vein to loop works. I wanted to write some code with you and talk about my ideas about what's happening in the background really is going to drive the point home. And then of course we're going to jump into what async and a weight really. I can't wait. 3. Macro Tasks vs Micro Tasks: Welcome, welcome, welcome. I'm super excited. I hope you dancing. I hope you're having a lot of fun. I hope you're learning a time. And thank you so much for sticking with me. We really have come a long way. And of course we're getting into video farms topics now. We have been discussing the event loop, but what is better than showing you? I know nothing, which is why I'm gonna show you the event loop in action. That's going to be quite interesting. Strictly speaking, I don't have to show you this, but I want you to become a grandmaster encoding. I don't just want you to understand basics of Ajax. I want you to understand what's happening behind the scenes. Of course, we're gonna be discussing async and await. But in order to understand async await, I just want to pause a bit more knowledge about the event loop. Remember one of the important things with the event loop is the concept of task queues. Functions, methods, to-dos or edit to a task queue. And of course you get different types of tasks. We get macro tasks and we get microtasks. But Clyde, we already know all of this. I know you do. So why don't we just play around in a text editor? Why did we have a bit of fun? Here we go. I've got a blank Visual Studio Code editor open. I've got one file called test.js. That's it. Now, I could just open the terminal, we could just console log everything to the screen. We could execute our JavaScript in the browser. There are many ways to do something in programming. I'm going to show you yet another. Now I want to implement the debug mode in Visual Studio code. So I'm just going to click on that tab. And I'm going to click on this, create a launch dot JSON file. And let's use Node.js to taste. Of course, Visual Studio code automatically creates this launch stop JSON file. I don't want you to stress about all this. You don't have to know how it all works. Or I'm wanting to get to is this debug console that's very, very useful. What do I want to do? Well, let's just console log something to the screen to start off with. And I don't know, let's just console log console one. How's that? But what's nice with us? Debug environment as you can put breakpoints in your code, you can step into your code. Very useful. But anyway, here I'm just going to run this code. And in our debug console we see the results. It's console one. That's a watered by the way, my favorite push animal. There we go. What do I want to show you? Well, let me ask you this question. Instead of cooling it console, I don't know, just cool it. I didn't know synchronous because we know the function console log runs in asynchronous way. If we have two like this, right? What do you think will happen? What do you think the result will be in our debug console? Let's write, we know JavaScript and Node fit meter is single-threaded. We know the first line will execute synchronous. One in the parcel will go on to the next line and net will execute. All right, so let's run it. We got exactly what we would expect. It's thought getting a bit more funky. Let's add a macro task. Remain macro task. For example, the setTimeout method, macro tasks we know or edit, toss, queue and executed the mixed brown of the vinculin. That's what a macro task is. And we know setTimeout method, which is asynchronous. It is a macro task. I'm just going to use shortcuts. So it's very easy to read. And all I wanna do is I want to console log. I don't know, let's say timeouts. And we can have a picture of a giraffe. And we know the second argument to the sixth timeout function is how many milliseconds we want to wait. Well, in this case, let's say Sarah milliseconds. Very simple example. Now I want you to think What's gonna be the result in our console. What's going to happen if we execute this code? Let's run it. It's pretty much what I'm sure you were expecting. The first console, it runs on the main thread. Now we get to the sit timeout method that is added to the macro task cute, aka it's being run off the main thread. Of course what that means, even though we want to console log the results of that timeout immediately, it's still off the main thread. And while it temporarily resides off the main thread, we get this console log, which again gets executed on the main thread, which is why console log synchronous one happens first, console log synchronous to happen second. And then finally, almost instantaneously, let's say timeout method, edit back to the main thread and then it gets executed. Interesting. But now, why don't we deal with promises? Remember, ajax is all about promises. And we know that promise is not a macro task. A promise is a watt. That's right. It's a microtask. And we know they are edit to the micro task and they are executed before. This is the key difference between microtasks and macro tasks are executed before the start of the next. Why didn't we use the promise object and we execute its resolve method? Of course, in real life, you'd have a whole lot of code and then execute the resolve method. Then of course, let's execute our callback within a dean. We don't need any arguments, so we can just console log something back to the screen. In this case, why don't we just grab our giraffe? Instead of calling a timeout, we can call it promise. What do you think will happen now? This is getting a bit trickier. You need to think about it. What order would you expect to see things? I would expect to see synchronous one, that console.log that first one on line one. That would happen instantaneously. Now what's interesting is that the setTimeout we know is going to be edit to the macro toss Q. The pulsating is going to go to the promise. And when it hits that promise, a promise itself will be on the main thread. But when the pulses sees the lean method that will be executed off the main thread. In fact, it's going to be added to the microtask cute. The possible then hit the lost console.log. The synchronous to line would show because that's gonna be executed immediately. So I would expect synchronous one, synchronous to show first, because the promise statement is on the micro toss Q out to expect debt to be issued back to us first, the giraffe promise, then finally the giraffe timeout. Let's see if I'm right. Let's hit the Run button and let's see what happens. Exactly what we would expect. Super, super interesting. Can you see how fun this is? Can you see how intuitive this all becomes? Okay? This is just a warm up. I want us to take a break here. In the next lecture, I want us to get more advanced, not cutting it at that. I want to start creating our own promises. I know exciting. I want to use a while loop so we can kind of see how it blocks execution or injuring of other functions. And it's gonna be super fascinating. This was just a warm-up. I'll see you in the next lecture. 4. Creating our own Promise: Welcome back. Hope you're having a lot of fun. And like I mentioned, this gets more complicated, so let's delete everything. Oh, man, I hate deleting all my beautiful work. Anyway, let's continue. What I wanna do is I want to implement timestamps throughout our code. Now, just to show you how to do something new. In order to do that, I want to start with getting the time right now before we execute the code. It's very easy to do in JavaScript. You can just excess JavaScript's date object and execute the nominated. Very simple. Next, I wanted to create a function that console logs something to the screen. I don't want to be writing all the time. Console log. Implement that in a function. So why don't we create a function and call it output for lack of a better word because that's what an output. It's going to take an argument. Let's just say for lack of a better word, that can be what we pass into it. And what do we want to happen? Well, like I mentioned, I want to implement a console log function. Simple. What do I want a console log? Let's put this in template literals want to console log. Firstly, whatever we pass into the output function, I want to actually console log that takes itself. The next thing I wanna do is I want to implement a new line. Then I want to show how much time it took to execute that function. I want time elapsed. In other words, that is going to be what? By the way, the dollar sign curly brackets inside temperature joules just means that we can reference variables and write JavaScript. It's very useful. So what we can do is we can get the time right now after the code has been executed, which is date dot. Now we resold it. We can deduct that from our mouth variable that we defined at the beginning. You know what, Maybe it's better not to call this now. Maybe I should call this begins because that's our beginning time, just so it doesn't confuse you. I hope that's making sense. Let me just zoom out yet to slightly so you can see it all in one line. We just finding the difference between the time now and the time when we started executing the function. Very simple. Let me zoom in slightly. What I want to do next. Well, I wanted to define a blocking function. It's gonna be a very simple function. Well, I want to do is I want to create a loop. So let's define a variable i starting at 0. And then I'm going to use JavaScript's while function. This will execute all the time, provided that what's provided in this parenthesis is true. We're going to say it's going to execute while I is less than, I don't know, just a very large number. And then on each iteration or I want to do is increase line. You can see we not doing much. Oee. And then when it's all done, when this while loop is finished, the code will then go on to the next line. And then we can just return something. What do I want to return? We can just return text. We can say done enough to put a nice pretty owl. Yeah. I've got an owl in my garden by the way, and I want to build an owl box. So excited. Anyway, I think that looks pretty cool. All done. There we go. That's our blocking code. And now we've done, all I'm gonna do now is execute these functions and I want to ask you what's gonna happen. So firstly, let's see it. Our output function we defined above. Remember we're going to pause it in some taste. What tips do we want to pass into it? Well, we can pass it on ice, will talk, and then we can just look at an asynchronous, which is what we did before, synchronous one, what do I wanna do next? Well, I want to execute our output function again, but this time as an argument. Remember we giving it an argument x. I don't want to pass in simple text. Well, actually I do. But I want to pass in our function which will ultimately return. I'll take saying all that. In order to do that, we can pass in the function, we can execute this function blocking. Then finally, you guessed it. I want to do another synchronous console log, but this time of course it. Alright. Let me ask you this question. In what do you think the result of this code is going to be? What's going to be displayed to us first. Well, I would expect synchronous one to show first, That's right. D naught. Well, we've got this blocking code and it's nothing asynchronous about that. While loop in JavaScript is very simple, it runs on the main thread. So when the parser, when the agent hits this wild function on the main thread, it's going to stay on the main thread. And everything else is going to have to wait. Boring. I know this is bad user experience. Then finally, when that while loop is finished, we get to the final output synchronous tool. Let's see if I'm correct, that's launches runners. And look at that. Synchronous one time elapsed was 0 milliseconds. That's how quick it was. We get onto this mixed while loop, You know what 80 milliseconds is also but, but short water and add a few more zeros. Let's run it again. Just to make it a bit longer. We get synchronous one and then it elapses and we finally get to synchronous. Two very interesting, Very interesting. I know, I know. That's why I wanted to show you. But now I want to pose you another question. How do we stop this blocking code from happening? How can we stop it? How can we turn this into an asynchronous piece of code? What do you think? Remember what we wanna do is I want to create a separate thread. I want to get off that main thread while that while loop is running. And of course we net while loop is finished. I want to add that return statement to the microtask. Cute, That's what I want. How do we do it? You might think, yes, we can create a promise. You might be correct, depending on how you thinking you strike this promise. Let me show you what won't work. So let's just comment this out. Now we should actually call it unblocking. For lack of a better word. How could we do this? Well, you might think, let's just return a new promises. It's execute JavaScript's promise object. We know that it will give us back resolve object and a reject object. We know this from previous lectures. We can execute our callback within these curly brackets. You might think that we can implement our while loop here. I equals 0. Implement while. How many zeros do we do this? Just copy it. While I is less than whatever that big numbers. Well, we want to do is increase I by one. When it's finished. We don't want to return anything. What do we want to do is we want to call the result method and resolve method. Of course, we can just have this saying hold on. Okay. Are you with me? Sorry, false. So we've tried to let's actually delete this. We've tried to convert the blocking code to unblocking by implementing a promise. You know what they mean? Get rid of the capital again, my OCD, not a constructor function. So let me do a lowercase u. You might think that we've implemented in our promise. This promise happens off the main thread, and therefore everything happens as we would expect gonna be unblocking. Now, you might think synchronous one will show first. Then, because the unblocking code is off the main thread, we should see synchronous two. And then finally, when it's done, we should see the result. All done. That this is not going to happen, will it shouldn't? If I'm thinking correctly, let's launch this program. Let's see what this happened. There we go. So you saw that actually, even though we're trying to execute a promise, it's still blocking the execution of our next synchronous output. That's why we only get to synchronous two in 143 milliseconds. A so weird, Clyde, I'm so confused, I thought because we wrap this in a promise, that means that we will execute this entire code off the main thread. It can get very confusing. But now there's something very advanced I wanted to share with you. Are you ready for it? So it's going to blow your mind. Just remain but the actual creation of the promise itself and that execution of the while loop, which is happening in the creation of this promise that is still happening on the main thread. Here's the thing. Promises themselves are just monitoring tools. They are not actually asynchronous themselves. Weight is asynchronous, fit in when it comes to promise. It fits in. When we execute the vein statements. When the engine sees a Dane statement, it takes what's ever inside the theme statement off the main task of the main thread. And only when net result is ready does it get added to the micro task. In other words, it is only the resolving of the promise in a vein statement that happens off the main thread as a microtask. Very, very fascinating. So that's why the first synchronous console log line gets executed right away. That this second synchronous log only gets executed off the while loop is done because the creation of that promise is still blocking the main thread. I'm sorry, I didn't mean to keep repeating myself, but this is such an important concept for you grasp and it's going to help you. Then let me ask you this. How do we then no pun intended. How do we then solve this issue? How do we ensure that that while loop is happening off the main thread? Well, of course we want to execute the resolve method and then put it all within 18 statement. We don't even need this reject property because we never use it. In fact, I can delete this entire thing. We can immediately execute the resolve method on this promise. We know in it's executed, the engine's going to look for the vein statement. And this is where our code can lie. They may actually put a TIA. We don't need any arguments. It should work. I think we've got enough brackets, they should work. Now the while loop is within a Dane statement. We should expect this now to happen off the main thread. It's now execute this code called type area promise resolve is not a constructor. Of course, not only the new keyword. Quite handy having error messages there. Alright, let's go now. And there we go. This is awkward hand. Let's just see here we get another reference error. Resolve is not defined. Of course I'm calling the resolve method here. I actually just want to return this because we within vein statement drive, they'll city. Of course I don't even need brackets. It's just pointless. Let's try this again. Sorry, third time, lucky, Let's go. That's a notice we're not getting our old done statement. Why? This? Interesting again, just remember what we're doing here. We've created a promise and this promise return something. At the end of the day, it's going to return a string saying all done. The problem we're having is we never accessing that return. Remember what a promise expects? It expects to give us the result. And then we can exit that results in a dean statements. So we actually have to call out I'm blocking function. And then when we've got that daughter, we went to execute some sort of function. The function we want to execute here is that output function. We can just execute that output function. This should work. It's a quick and dirty way, but it should work. Output. Let's see if this works out. Let's now run our code. We did it, We did it false time, lucky. Sorry about that, but we got there in the end. Just remember what it is we've done. I'm trying to show you that a promise, the actual creation of a promise is done on the main thread. It's only when we start hitting these links statements, aka when the resolve method is called. Do we then get off the main thread? And that's where the asynchronous magic happens. I just wanted to make that clear. That's why here we get synchronous one given to us back first, we get synchronous two given vectors next. Then finally we get this return statement of all done. By the way, you might be thinking, why did I just put the function name outputs? Don't I need to pass in a variable x. It is pretty much doing that behind the scenes. I could've been, if argument's sake, we could have taken the data. In this case, it is just going to be the text daughter all done. And then we can write it after the usual way that we used to in this course. And then of course, execute that output function and we pass in that data. So we could have written a Titus. I just did a shortcut. If we run this program again, that should give us exactly the same thing which it does. I know, I know this is pretty advanced, well done for sticking with me. And you don't strictly need to know this in order to work with async and await. In fact, you don't even need to know this when working with Ajax. But I want you to be better than the race. I hope you've had a lot of fun and I hope this is just ******** some more light on how the Vancouver works and how asynchronous code works. In reality, they aren't two main threat doesn't work that way when it comes to JavaScript. But at x lacquer does. If I could take things off the main task, you put them back on. It's very interesting that enough of the event loop now, I think you've got enough of a high-level knowledge about it. The next lecture, I really want to start talking about async and await. We want to improve our Fetch API faculty. I can't wait to see you in the next lecture. 5. Intro to Async / Await: Finally, we are on the topic of async and await. What exactly is it? Well firstly, we can add async and await. These are just keywords provided to us by JavaScript to reduce our statements. Remember when we're dealing with fish calls, with dealing with promises. And every time a promise resolves, the first thing statement will get executed inside that thing statement. You need promise returned, will then look for the next dean statement. So in reality, as we've seen, you can have multiple vane chains. This can get quite confusing. Trust me, especially if you've got very complex code and you've put a lot of promises being resolved. A workaround is to use async and await that allows us to write code in a synchronous way. Even though all these promises are happening in the background. Don't worry if you don't know what I mean, I'm gonna show you shortly. The point I'm trying to make is that using async and await works very well with Ajax because you use async and await when working with promises. And of course we know that Fitch uses promises before we talk about await. Remember the two keywords yet, async and a weight. I want to talk about async, not in-sync, not a sink. I love my dad jokes. I want to talk about async and putting the word async before function. It means one simple thing. Don't get lost in all the detail. Just means one thing. What does it, what does it tell us? What is it doing? It's telling the function to return us a promise. What weird, but there is nothing better than showing you with a live example. Let's hop over to the Text Editor now. 6. Async returns a Promise: If you know the drill, That's create a new file. Let's just call it for lack of a better word, messages ab.js. Because I'm going to create a function called message. That's why let's create a function called message. In order to do so in JavaScript, we just use the function keyword. We can call it anything we want. I've called message. Then within these curly brackets we define what we want to happen. Yeah, I just want to return the word Hello. That's all I want to happen. Yes, I could execute this in the browser. Then we can see the results. Why don't I just use coca? Ithaca allows us to run JavaScript real-time in this text editor, it is very, very useful. It's free by the way, my voice loved Mahila. Alright, what I want to do, let's console log this function. Yes, we would expect the result to be hello, which is what you seeing on the screen. That makes intuitive sense. But remember what I said in the lecture. Async can be used before any function. That's pretty cool. So what did we edit in front of our function? Remember what I said? Using async means one thing. Instead of function will return a promise. So let's test it out. Let's put async in front of our function. Now when we execute this function, we don't get that text Hello, we get a promise. Isn't that interesting? That's all that it does. That async keyword returns a promise, but Clyde, can't we just explicitly return a promise? We can, instead of returning Hello, can't we just return a price? What do they do? That gives us exactly the same thing that gives us a promise, of course this time That's not going to resolve to the word Hello. We don't have it in their animal. And so what we could do is we could execute the results method. And on here we can type the word hello. It's exactly the same as us doing that by putting async, then we can get rid of async. We're gonna be getting exactly the same thing. So instead of writing that big long takes lie name, we can put the word async. And of course we don't need now promising results. We can just return whatever we want returned from the promise. Is that making sense? Are you with me? Sorry, fall. That's all at the async word does. Async ensures that the function returns a promise. Simple enough, doesn't only do that. There's another keyword I'm leaving out. And that is a wait. Wait only works inside functions with the async keyword. Some thunder outside, it's raining, it's raining. We needed though. We haven't had rain in a few days. Anyway where it was on. Yes. We've only discussed async that returns a promise. But in the next lecture, I want to start showing you about the await keyword. I can't wait to show you. 7. Intro to the Await keyword: Hall, all good things come to an end and a bit sad because I know we approaching the end of this course. But don't worry, we're not quite done yet. We're not quite done yet. And I'm always coming up with new courses. So I hope we weren't pathways here forever. But anyway, we are talking about async and await. We looked at what the async keyword does. Do you remember? That's right. Async ensures that the function returns a promise. We could do this manually, but it's just cumbersome. So async is just a nice handy way for us to tell the function to return us a promise. We know that. But now I want to talk about await. The first thing is it only works inside async functions if you try and use the word await in a random function in some code, It's just not going to work. You have to use it inside a promise, inside a function with the keyword async. Await, do, I guess the actual word itself gives it away. It makes JavaScript wait until their promise settles and returns its result. Very, very intuitive. Take a step back though. Don't get lost in all the detail. The purpose of async and await is to simplify the syntax necessary to consume promise based APIs. You don't have to use async await when you make a Fitch ajax call, you could just do simple future quizzes with all those then statements and catch all areas in the catch block. That's perfectly fine. However, sometimes it can get messy, sometimes it gets confusing. And in those instances where your code starts getting a bit messy, often, you want to resort to using async and await. It's just much easier to read. It's much easier to follow. The way I think of it is that I take an async function. Inside this async function, you can think of it as being split by 0 or more a weight expressions. And your code within that function up to and including the first await expression is run synchronously. We know that synchronous execution happens automatically by default in JavaScript. And it's only if and when there is an await expression inside of their function. Does the browser know to execute this code asynchronously, aka off of the main thread. It's very, very interesting, very intuitive. But enough talk, enough theory. Let's hop over to the next lecture. Let's stop here. And I'll show you an example of using async and using a wait. I can't wait to see, you know. 8. Example of using Async / Await: Actions speak louder than words, which is why, you know, I love my examples. So let's now use async and await, and I'll show you how it works. It is very, very interesting. I wanted to find a function called message. Then I want to execute a whole lot of things inside here. We notice what I want to do is I want to eventually get the result of hello world. Eventually try and get to that result just text given to us by the console, but I want to do it by using two asynchronous functions. Let's split up each word. Let's first deal with the first word, put it in a variable called first word. And I want to now use promises. We cannot normally do this, creates a promise, and of course we know it gives us resolve and reject. We're not really using the reject property that anyway, it's there. If we wanted, we can now use the setTimeout method just to fake an API call. Let's just create time, a time gap. Of course, within here, I want to resolve the word hello because this is the first word we want, and I want this to take 1 second. We can't do this. Because why? That's right? Because we are implementing a promise. The results will not be available in that variable first word. So this won't work. In order to make it work. We want to turn this entire function into an asynchronous function. We do that by using the async keyword in front. We now know that this function is going to return us a promise. But again, line four will still not work. We're going to get an error. You don't believe me. Let me show you. Let me show you. At the end we want to console log. I don't know, Let's use temporary literals. We can say done. And of course here we've got first word. This is not going to work. It's now execute our function called message. We not getting the results we would expect. In fact, let's go to the browser. There we go. Let's paste our code that's executed the message function. There we go. We get undefined. We getting errors here. That's a problem. We don't want this, we just want the simple message, hello. Not going to work because this first word, property variable, it's not available yet in order to wait until the promise resolves and they inputted into that first word variable. We use the await keyword. This is how easy it is to work with async and await. Well, That's the first word. Before I move on, let's just create a second word. First word. Yeah, we can call it second word. And we know the second word is fooled. Here we go. So when we console log and done, we can say first word. Of course we can have resolvers, not the fine, of course results not defined. And I've called it RES. Know what should I change? I can either make this result or change at arrays, but let's just make that resolve. There we go. Now of course, when we execute this message function, everything should go according to plan. Does co-occur tells us that we get console logged, done. Hello World. But my dear students, I want you to understand why. Let me just zoom out. Let me scroll up. This is our entire code block. Let me explain what happens here. And this is gonna be very technical, but it's very, very important for you to understand this example. We awaited to promises. What's going to happen. Well, okay, let's talk about the code that gets executed. We know that progress moves through this message function in three stages. Stage one, the first line of the body of the function is going to be executed synchronously. This is the default behavior of JavaScript. This means we're going to hit line for, this is the first thing that's going to be executed. But now, when the parser hits that await keyword, the browser knows that there is a painting promise. It needs to wait for what's going to happen. Well, the result is that the progress of our message function is going to be paused and control is going to be yielded back to the environment that called the message function. In this case, I'll mix each function is called on the window scope and nothing else is happening on the main threats and nothing else is going to happen. But this is what's happening behind the scenes. Stage to sometime later when the first promise has either been for fold or rejected. Control is going to move back into this message. Function, the result of the first promise, hear the word hello. It's going to be returned from the await expression. Here. The word hello is assigned to the variable called first word. That's done. Progress will then continue. The past is going to now see the second await keyword. Again, the browser knows that there is a pending promise it needs to wait for and progress. And how many such function is now going to be paused again. And control is going to be yielded back to the environment. That cold message. We just repeating the process here. Last but not least, stage three, sometime later when the second promises either been fulfilled or rejected, control is going to reenter this message function. Of course, the result of the second promise resolution is return from the second await expression. In our example, the word world is assigned to a variable that we defined as second word. But now's the key difference because now we don't have another await keyword. Control is going to move through this message function, eventually hitting a return expression. Here we're just console logging something to the screen. Have you got it? Told you this is very advanced. I hope you're understanding, I hope I'm explaining till you enough really is quite intuitive once you understand how it works. But before I finish this lecture, let me just pose you one more question. Remember I said that when debt await keyword is hit by the parser, I said control is going to be yielded back to the environment that called, that makes IT function in the first place. Remember I said that and he has the window environments and nothing else happens. But what do I mean? What about if it's not the window object that called this message function? What about if it was another function? I know it's getting a bit complicated, but let me show you what I mean. Let's go down here. That's not execute this function now let's just comment it out. Let's say we have another function. And this function, Let's just call execute for lack of a better word. And inside this function, we want to execute this message function. And we want a console log am first to the console. Right now I haven't executed this function, we've just defined it, but what do you think is going to happen now, based on what I said a few moments ago, to illustrate the street in a cheap copy, these two functions, browser, console. What's gonna happen off I execute this function. Let's try it. How awesome is that we get executed? I am first, first. And only once all those set timeouts have resolved that we get the word done, Hello World returned back to us. Or just students, how awesome is this? What's really cool with this though, is that you are understanding what happens behind the scenes. Because when the parser hits that first await keyword, that's going to yield control away from this message function to the environment, then call it, and that is this execute function. And it's going to continue to execute code synchronously. We know while it's paused and while that promises resolving, we know that that console log I'm first going to be given to us first before the entire message function has executed. The reason I had to go to the browser by the way, of course, if I execute this function now, why is it not showing anything? Coca-cola and show us the order in what things are done. So we can see here that we get, I'm first n, we get done. Hello world. We can't see the order of when it happened. That's why I wanted to show you here how it works. Let me show you again, you can actually see the time it takes to execute those timeouts as well. It's fascinating. So let's define our functions. Let's execute it. We get immediately, I'm first we got to wait two seconds and then we get that done. Fascinating. I want to stop here. I want to have a break. In the next lecture, I'm going to show you another quick example and named finally, I want us to use what we've learned. I want us to use the async and await keyword to improve code that we've previously done on other examples. I can't wait and I'll see you in the next lecture. Okay. 9. Second Example of using Async/Await: You know, I love my examples because I really do think examples drive the point home. I just want you to get very used to the concept of wind that await keyword is hits by the pasa. Progress of the entire execution in JavaScript is thin posed in that function and control is given to the environment that of course executed that function. I just want you to get used to that concept. So why don't we create an async function so we know it's going to return a promise. We use the function keyword in JavaScript. Let's just call it foo. This is just mock convention. I don't know why we use food all the time. It's just a made-up function. It's just a function name. We could have called it anything we want. I want to now define a promise and it's instantiate the promised constructor function. We know we've got x's to resolve and reject in our constructor function. Of course, what do we want to happen here? Just get all the brackets and all that sorted. We are ready to execute. All I wanna do is I want to implement the setTimeout method. I don't really want anything to happen other than resolving this promise. And we can resolve the word hello. How's it? Pretty simple in one hundred, ten hundred milliseconds. Here we go is all very simple async function called foo. The next thing I wanted to do, I didn't want to execute this right now. You know what I'm gonna do? Let's actually just write this in our state at the F, just easier to see what's going on. Of course, unless inhibit capital N for new. There we go. Now I'll text editor at least is telling us that everything's a K. Syntax is very important when it comes to coding. Obviously, your computer just understands 1's and naughts, aka electrical impulses. It's garbage in, garbage out effectively, if I make any error, if I don't, if I call this promise promises, the JavaScript engine is not going to understand what that is, gonna be. Garbage. So anyway, that's why the new keyword is very specific. And JavaScripts, I have to use lowercase mu. That was my error. Anyway, we're still inside this function foo. We've implemented a promise. The promise is going to resolve with the word hello in 1 second. Now, this is what I want to show you right up until this point we haven't used the weight keyword. What I wanna do is I want to define a message variable. And let's await this promise. To understand what it is I'm trying to do. I'm going to wait until the promise above resolves with the word hello. That's what I'm going to do. And then I'm going to put it into a variable called message. Interesting. Then of course what I want to do is I want to alert message to the browser. I want that little pop-up to come up and I want us to see the word hello. Let's go to the browser. Is clear, everything is define our function. There we go, we've defined it. Let me zoom in a bit given our conversations we've been having. Given the example I showed you in the previous lecture. I want you to think logically what happens here. Well, firstly, let's just execute this function so you can see what happens. We've executed it. Resolve is not defined. Let's clear this. I called it. Let's do raise. Here we go. And let's call the function again. There we go. And we get the alert saying hello. That of course happened after 1 second, as we would expect. There we go. This makes sense. But do you understand the logic now? Let me explain the logic tier. You probably know already, but let me drive the point home. Let's look at our code. The function execution is going to pull which line? Well, it's going to pause when it hits that await keyword. It's going to pause online in ate. We know whichever environment called this function foo, that pain will continue to be executed in a synchronous manner. When the promise eventually returns a result, then control is going to be given back to this foo function. Of course then we execute that alert message, makes sense. This is what I want to emphasize. Using the word await literally suspends the function execution and told the promise settles. It's then going to resume with the promise result. This doesn't cost any CPU resources because the JavaScript engine can do other jobs. In the meantime, it can execute other functions or the scripts handling beans, etc, etc. It's very, very powerful. But anyways, I think you've got a high-level understanding enough to start digging deeper into async and await. Before we end this section, this class, I want you to use what we've learned in a practical way. In the next lecture, I want to call up some code we've looked at previously. And I want you to try and convert that code or improve their code by using async and await. I can't wait and I'll see you soon. 10. Challenge intro - improving our previous class Fetch code: Welcome, welcome, welcome. If you having a lot of fun. Now, all right, Here we are. This is code from a few sections, classes, Beck and you know, the drawer we had this Fitch API that made calls to do different websites. The first feature request was to replace this hitting with our IP address. Mine is not working at the moment because I am in Zimbabwe, in Africa. And hey, sometimes we don't have power. Right now. I've got no power, no electricity. And that means, of course, no router and Wi-Fi. So I can't taste this code right now with you. But what I can do is we can improve our code, we can refactor it. The second face your quiz, we did the remainder to our own server, showing an image, click on the button and we show Ajax. If we go to our code, we can see here at the bottom of the file, this is our feature quest to Fitch that imagery. And there are a lot of themes statements. It's a catch statement. I want you to think about how we can change this, how we can improve this code by using async and await, give it a go yourself. Let's stop the lecture here. And in the next lecture, let me code it up with your conduit and I'll see you shortly. 11. Challenge solution - fetching our Image using async/await: Did you give it a go? I hope so. I hope so because that's the most important thing. It doesn't even matter if you didn't get it right. The most important thing is that you gave it a go. Let me do this in a piecemeal manner so you understand what's happening. You might have thought, Hey, we know that Fetch returns a promise. We deal with promises so we can deal with async and await. But even before it, you might think, hey, let's put this into a variable called response. And we can execute this fetch function. You know what? Let me just, let me just comment everything else out here. Let's donkey confused. You might have thought, okay, let's grab our response. We know that responses over readable stream you might've felt okay, well, let's try and extract the data by taking that response and executing the blob method on it. Because we know we're dealing with an image. It's binary data, it's not JSON. Then of course, let me actually just copy the next lines of code below here. You might have been saved. Let's define a picture URL by using the URL interface and passing in this data object. Might've tried to do that. Then of course, taking the image source elements and assigning it to that picture URL. Of course, the final step is to console log success to the screen. Is this going to work? Well, let's test it out and let's go to our browser. Of course, now when I click the button, it's not working. What error messages that we're getting. We're getting a type error response. Blob is not a function. Do you understand why? Why are we getting this type error? Well, if we go back to our code, just remember, the reason we're getting this era is that although we know the response object has the blob method, by the time the browser gets to the next line of code being online 97 and alkanes, the response object, that variable. It hasn't yet come back from the phage coal. Remember that Fitch call is being made on another thread aside three, that's being made in parallel to the main thread. That's why we're getting an error. Okay, client will want or not, then just add the word await in front of Fitch and await in front of the blob method, right? Those are the only two that return a promise, so we don't need to wait anywhere else. Will this work? Well, that won't work either. Let's go to the browser, refresh everything. Tick the button. It's not working. It's not going to work. Why isn't it going to work? That's right. Because you have to use await within an a sinc function. Then we just have to expand our code a little bit more. But you'll see it's worth it because it becomes very easy to read. Remember, we need the async keyword and then we need to define a function. Let's just say it's called Fitch image and everything resides within these curly brackets. Here we go, starting to make sense. Now, we've defined a function. We've put the async keyword day, we're using a weight. We can read it in a synchronous manner. And of course then we've actually got to implement or execute this function, right? Otherwise nothing will happen. There you go. This is how we use async and await. Is this going to work? What do you think? Let's go to the browser. Click the image. Wow, that is very, very cool, isn't it? Don't get lost in all the detail. It's very simple mount to read. I won't go through the logic in detail because you already know how that works. But just remember in our original code, if you scroll down here, we actually implemented a few other functions, check status and convert to blob. Right here. We bypass those things which is not good. We do want to check the status and we do want to put our logic elsewhere. If we scroll up, we've got the section called universal functions. We've defined certain functions. We've defined a function called check status. But what's interesting about it? That's right. It returns a promise. Interesting. And I'll function converts to blob also returns a promise because we know the blob method returns a promise. So why did we improve this code slightly? I think the first line is fine. Response is what we get back from our fit coal. Then we only want to deal with a good response. A response. I don't want to execute our blob function. What I want to do is I want to implement our check status function and we pass in our response object. We know this. Once we have that good response, the next tip is to convert it into a blob. So why don't we call it in a blob data for lack of a better word. And yes, we can execute our Convert to blob function. That will take our good response data. There we go. We literally done the should work. If we go to the browser, everything, click the image. Reference era, daughter's not defined. What have I done wrong? Data here should be blogged daughter course. Let's go back to our browser. Click Show Image. How awesome is that? How awesome is that? I'm very, very happy with this. My dear students, How cool was this? Now I want us to pause the lecture here. It will stop the lecture here. I want you to try and do exactly the same thing, improve the code. But if I scroll up, I want you to do the same for fetching the IP address. Here it is, the Fitch coal to get our IP address. Stop the lecture here, try convert this yourself. And then I'll show you how I did it in the next lecture. 12. Challenge solution - fetching our IP address using async/await: Did you give it a go? I hope so. I hope so. And I still don't have Internet here ends and we've got no power. So I can't taste it, but I will write it off with you. If it's not correct, please let me know in the Q&A and I'll fix it, but hopefully logical prevail and it will make sense. So how do we convert this? How do we fix it? Well, firstly, let's get rid of this entire block. If we don't need it. It's defined now an async function. We can use the function keyword in JavaScript. We can call it Fitch IP because it's exactly what we're doing inside this code block here we can perform our actual fit your question, what's next? What do we do? Well, I don't know. Let's just say our rural response. I'm just showing you we can define it. Anything we want is the result of this Fitch request. And of course I'm using the async keyword here because we know that that feature request returns a promise. What's next? Well, we want to check with it, we have a good response. So let's define a variable called good response and execute our check status function, which we pass into it, our rural response. You can really see this is very, very simple, it's very intuitive. We know once we have the response back from that FetchRequest, we know to redouble stream. We know it's Jason because we making a call to this world time API URL and it tells us that we get given back JSON data. What we want to do is we want to actually define a variable called data, which is going to be JSON. Actually it's not, it's gonna be a JavaScript object, but we know it's gonna be the result of as having cold the JSON method. We use the keyword await once again, if we take out good response, we know it has this JSON method. Now let's JSON method. We know from previous lectures that debt returns us a promise. That's why we have to use the await keyword. Of course, we can finish off the same tire example. By grabbing our IP takes query selector. We can grab our HTML element that has an ID of IP takes, I think that's what we call it. This is scroll up. These are header IP takes, Can you see it? Let's go small t. If I p takes, Let's just do small teeth. This change its inner HTML property to what we know on this JavaScript object. Let's give them back to us. It has a property called Client IP. We've done this before. You know what I'm talking about? This should work. Actually it shouldn't because we haven't executed a function yet. So of course, outside of this code block, let's execute this function. Mit students, this should work. Like I mentioned, I don't have power. So it's not going to work for us. That's why this hitting taste has not been replaced. But you get the point. I think that logic will stand if there is something wrong with it. Please just look in the comments. Some shorts been resolved already. But yeah. Yeah. Hope you having fun. I'd be having fun. There's just one more thing I want to mention. That is eras. Right now. We're not catching errors here. You know what, let me delete plus now let me keep the common day. It's fine. But right now if we go back to our image, coal, we're not dealing with areas. In the next lecture, let me just quickly show you how we can use a try and catch block to deal with errors. I can't wait. 13. Error handling using Try and Catch: The final thing I want to talk to you about is error handling. I mean, we know we've executing check status convert to blob. And if we go to these functions at the top of our code, we do have some error handling. We call it reject method. For example, if the response okay, property is false. But what happens if we have other areas? What about if we have areas not in those code blocks? Well, there's a very easy solution to this. And that is, we can wrap our entire code block in a try statement. Very, very useful, very, very intuitive. So we just move our code all within this try-block. And what that does is it allows all areas to be caught by this catch block. Course, we get given back an error object which we can put into any variable. We putting it into a variable called Era. And then it will execute this callback function are medically and of course you can do whatever you want. This just console log that air object bet to the user. Okay, So we can literally just do this, put it in a try and catch pockets. Very simple. I told you, I told you it's not going to be difficult. And then you have an error, like an incorrect URL. Go to the browser, go to the console, and click the image. We get an error. And this is our custom error. Let me just prove it to you. Hello World. We got, Let's go back to the browser. Click the image, and then we go, Hello world. Oops, this catch block is actually catching the error. I hope that this is all making sense. If I had a lot of fun in this false, we have covered a ton of information. Taking a step back, I want you to realize that you really have come a long way. You know what JSON data is, XML data, you know the history of Ajax, where it came from. You know what a constructor function is that we used to use the XHR object. And list goes on. Walden, pat yourself on the back. There, we have it. Very, very simple. This was very quick lecture. I hope you can start seeing the power of using async and await.