Callbacks, Promises, Async Await | JavaScript Fetch API Explained

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments

In this video, we will look at how to use Async / Await with the Fetch API. First, we have to understand the concepts of callbacks and promises. We also need to understand thenables and how async / await replaces them in our code. The first 30 minutes covers the concepts. The last 30 minutes gives examples of retrieving data from different APIs.

Subscribe ➜ https://bit.ly/3nGHmNn

✅ Quick Concepts outline:

Fetch API with Async / Await

(0:00​) Intro

(0:29​) What is a callback function?

(1:15​) What is the problem with callbacks?

(3:00​) JavaScript Promises have 3 states

(5:28​) A promise may not return a value where you expect it to: You need to wait for a promise to resolve

(6:58​) Using thenables with a promise

(20:15​) An easy mistake to make with promises

(24:00​) Creating an async function

(25:00​) Applying await inside the function

(33:45​) Example 1: Retrieving user data

(40:00​) Example 2: Retrieving dad jokes

(47:00​) Example 3: Posting data

(49:40​) Example 4: Retrieving data with URL parameters

(54:55​) Abstract it all into single responsibility functions

🤖 APIs used in the examples for this tutorial:

https://jsonplaceholder.typicode.com/

https://icanhazdadjoke.com/

https://httpbin.org/

http://www.icndb.com/api/

Was this tutorial about the JavaScript Fetch API, Async/Await, Promises, Thenables, and Callbacks helpful? If so, please share. Let me know your thoughts in the comments.

Async Await Javascript with Fetch API Examples: https://youtu.be/VmQ6dHvnKIM

👍︎︎ 1 👤︎︎ u/DaveOnEleven 📅︎︎ Feb 14 2021 🗫︎ replies
Captions
hello and welcome today we are learning about the fetch api along with promises then-ables callbacks and async await let's get started today our main topic is the fetch api but that also requires a discussion of callbacks promises venables and async a weight so we'll start with callbacks callbacks are just functions really that are passed to other functions as parameters so they will call that function after they finish doing their other stuff so a quick example of defining a function with a callback we'd have the word function and then let's just call this first function and we might have a parameter or however many parameters we want and then we could have a callback and that callback is a function so in the function we would do stuff with the parameters or whatever and at the end we would call that callback function and that allows us to call a function that in turn will call another function and it essentially is a chain of events well promises are designed to get rid of this but let's show you the problem and the reason people wanted to get rid of this this could be called and is also known as callback hell i don't know if i would call it hell but it could be a problem and what happens and how this code looks when you use callbacks if you're using several consecutively say you'd have your first function and you'd pass in your parameter and then you would have your space for the callback parameter and here you could put in an anonymous function and now inside that anonymous function you would call a second function that's designed to also have a callback so it could have a parameter and then you'd have an anonymous function there and then maybe you've got a third function that does the same thing and it could have a parameter an anonymous function there and you can see what's happening here and each level you go deeper and of course there could really be things in between here like we're doing stuff here after a while your code can get a little hard to follow and each consecutive function that has its own callback is another level of indents and the code just gets a little hard to follow and you probably see this in some legacy code before promises existed because this was a common way of doing things but it is also called callback hell and promises are a way to get rid of that so now let's look at a structure without callbacks because we won't be using those but at least you understand why we've moved on to promises so with promises and i'll put the focus here on promises they can have three states so we need to understand each state of promises one is pending another is fulfilled and the third is rejected now promises will deliver async code javascript is usually synchronous meaning doing one thing at a time but a promise is kind of like hey man i promise i'll pay you back tomorrow if you loan me the money today or you go ahead and i'll catch up once i'm finished with my task over here so a promise could be pending while some other javascript code goes ahead and executes promise it can be working on it in other words so you're actually executing two different blocks of code at once in that regard so let's look at a promise i'll just define it as my promise and there is a promise object so we'll use that for this example we'll say new promise and promises can resolve or reject and then pass this along we see that's in an anonymous function and in this resolver reject i'm just going to define say an error variable right now i'll set it to well let's set it to false to start out with then we'll say if the error is false we're going to resolve and in this will say yes resolved the promise and then else will reject there we go and we'll say no rejected the promise okay now that we've defined my promise oh i've got an unexpected token a typo there there we go okay now that we have defined my promise we can use my promise and i'm going to show you an example here you'll be tempted to do this but it won't work but this will let me display the state of the promise though and then i'll show you why this won't work we'll just go console log my promise now we would expect to get the resolve value here because promise is false and if promise well if the error is false this value is false and if this is false it's supposed to resolve and it would return yes resolve the promise but let me show you what actually happens we get promise fulfilled and then you see yes resolve the promise but this is the state of the promise this is not actually returning the value like we would work with the value in our program instead to get the value out of a promise we need to chain remember how callbacks in that example were chaining because the first function that had a callback would call the second function in its callback position and the second function would call the third function they were chained together so promises can also be chained together and with es6 when promises first came about around 2015 i believe uh we did that through chaining venables and that's the next word up here is the focus is a venable so let me show you an example of that before we get to a sink a weight which async a weight of course will replace the venables that we used at first with promises but let's look at the venables first so here's my promise now instead of logging and just trying to get that information and of course that didn't work as you see here in the console we saw the state but we didn't really get the information we need to go dot then and then let's look at the value that the promise delivers and this is an anonymous function and we can log the value now i'm going to save this and we can compare now you see in the console instead of getting the state of the promise which is fulfilled we actually got what the resolve returns from the promise and that is yes resolve the promise and then with a thenable you can add another then and do something else let's call this new value and let's look here this this of course is another anonymous function so here we can just return value plus one whatever we just modify the data and then that will be the new value passed here because new value is the parameter for this anonymous function and then we'll console.log new value and you can see now it has the number one after the exclamation mark here because we returned value plus one and it went down to the next then and sometimes you'll see it with the then on not on the same line as the promise or you could have it all in one line actually because these are just chained together as we do with methods as well so we've got the promise and it resolves and then we return the value from the promise plus one then we log the new value now if there's an error let's look at that so let's change this error to true and let's look at what happens in the console now the promise state is rejected and this says uncaught in promise we didn't really catch this error and then we see no rejected the promise but we can catch an error in chain venables what we do at the very end is chain a catch and this catch can also have an anonymous function and it passes in the error object and we just say console. let's go with error and pass in that error and now when i save this you can see on line 27 which is where we log the error we caught that error and if an error happens anywhere along the way in here including in the promise itself it goes through the chain and at the very end it just logs that error so it could skip the rest of the chain actually whenever it encounters that first error it goes straight to the catch and you've got no rejected the promise so that is how a promise works you've got i'll give you an example of course of pending here very soon we've looked at the state of fulfilled we've looked at the state of rejected and this is a promise now the fetch api returns a promise on its own we don't have to create a new promise and i'll show you that here in just a minute but this gives you an idea of promises and the fetch api does return a promise okay before giving you an example of a pending promise let's look at a reason we have these promises just like replacing the callbacks we mentioned another reason and a big reason of course for using the fetch api is requesting data from another server or another site out there on the web and what can happen is we can have to wait we need to wait for that data to come back before we can work with it so we need to tell our code hey wait for this and then do this after we get it and that kind of makes sense when you look at the chain of venables but before we work with fetch let me give you another example and one way to kind of oh i guess simulate uh how fetch works is to use a timeout in javascript and that is to delay the execution of some code so i'm going to create a second promise here and i'll call it my next promise and this is going to equal a new promise and it will also have resolve and reject as our first one did in that anonymous function okay but inside this one i'm going to use the set timeout function in javascript and this is part of the window object so you could have window.settimeout but of course you can omit the window now this is an anonymous function and to spell that out i'll use the keyword function and whoops put the operator there and then i'm missing that there we go so that is a callback right there for the set timeout and then it accepts this function and then we can put in exactly how long we want to wait and i'm going to tell it three seconds so it'll be very obvious that hey there's a delay before this code executes now inside here we'll just put resolve and then we can put my next promise resolved and so after three seconds we should get that return from this promise and now we can call both of these promises in much the same way so let's say we're going to call my next promise first in our code and then we'll take the value from that and we'll log the value and then we can do the same thing i'll just copy this with the first promise and so we've defined a couple of promises and then we call my next promise first and then after that we call my promise let's go ahead and see what we get in the console oh of course i left that as a error let me go ahead and change that back to no error so that doesn't happen so we resolved the first promise and then three seconds later my next promise resolved even though we called my next promise first we call this into action right here of course we saw the result from my promise first because of the three second delay which here's a three second delay which is a a pretty big delay as far as javascript goes but i just wanted to make it clear that that delay happens and maybe we need to wait on some code coming back from another server before we can move on and this is an example also that shows you that javascript really doesn't wait it's not built into waiting but this is an example of my next promise going you go ahead you go ahead and run the rest of the code and all catch up and that's exactly what happens because we see the result from my promise before we see it from my next promise okay now that we've explored promises completely and we're ready to look at an example of the third state that i haven't shown and that is the pending state of promises and we need to do that with the fetch api it's an easy way to display that so what i'm going to do is define a variable called users and it is going to be equal to the promise that is returned from fetch now fetch will request data from another place on the web for example so in this example i'm going to use jsonplaceholder.typeycode.com and we're going to request users this is a great site to get some example api data from and that's what fetch will work with and in this result we should get a pending state of the promise because i'm going to attempt to log the result of the promise right away of course you don't want to do this when you're trying to actually work with the data from a promise this would be a mistake but it will display the state of the promise so let's take a look and we get a promise pending that's because this promise has not resolved it is still kind of working on it it's that where i said go ahead you guys i'll catch up i've got some work to do and so the rest of the code goes ahead but the promise is still working on it so we attempted to log the user's value essentially what would be returned from the promise while it was still working on it and that's why we need to wait and we wait uh traditionally with venables we say okay promise finish up and then do this so let's look at another example of that and i'll take this same fetch and after the fetch instead of just ending right there with the semicolon i'll put then and we get our response from the api once we get that response it's not really ready to work with yet and we could log that i guess but i also want to show you why it's not ready to work with i guess i'll save this first we'll log that response and here you see the response but once again it's not ready to work with we really want json you can even see that in the name of this api json placeholder but we want json to work with and this is a readable stream so we'll look at the body we get and we see this right here and it says readable stream it's not data we can work with quite yet so what we need to do is call the json method of that readable stream that that's available here the body that's actually a body mixin is how it's referred to in mdn so what we'll do is take the response and then call the json method for that and we'll return this response here so instead of logging that i'm going to return that and now we'll have json so then we need to go to the next den now we have our json data i'll just call it data and here let's log the data we get from the api and you can see we get 10 objects back from the api's 10 user objects and we can expand that and you can see each one of these has information about the user from the api so once we've got the data we can work with it but we need to remember that it's within this block of this anonymous function we can't just suddenly take the data out into the global area here because that's not executing the code in the same order this is saying grab the data from the api with fetch then turn it into json and then work with it here but outside of this in the global space it will go ahead and execute code below the fetch in our file before this is complete and we could look at an example of that as well but first we'll go ahead and say data for each and then i'll put whoops user and let's just log each user and this is an example of working with the data in this chain and now we've got in our console a log of each user we pulled that data right out of the json and pulled each user instead of returning 10 at once so like i was talking about the example of not trying to refer to this data if we had this let's call this users again we can get rid of this what we have up here and i'll just say users equals fetch we're going to kind of run into the same problem we had before because if i think i'm going to get that data from users and just log the data here or whatever is in users we're going to run into the same problem you see user's logged first and it's that pending promise on line 18 then we get everything on line 14 because this has to actually go get the data and come back and it's waiting but it's a promise and it says hey javascript go ahead and execute the rest of the code while i'm doing this and that is why line 18 is executing and we see the promise pending before we get these results this line does not wait on this code and that is the main thing you kind of want to understand at first about how promises work and fetch returns a promise so we're working with promises also this method here the json method of the body mixing returns a promise so each one of these is returning a promise as we go through the venables chain so we have to consider that and say okay this is going to happen and then after it happens this will happen and then after this happens this will happen but this or anything else that we just put that's outside of this then able chain for the promise is not going to happen in that order it's going to go ahead and execute and not wait on this now what can happen also with data that we get in this manner we could continue to work with it and although it's not call back hell as we previously described we have then and then dot then and dot then and this can kind of get out of hand too and you can have a huge chain of venables and that is also not desirable and about i believe yes 2017 maybe 2018 but i think it's 2017 is when async and await came about their keywords kind of syntactic sugar that hides what's going on it's another way of telling your code wait for this to happen before i do this but it lets us write the code in a much cleaner manner in how we're used to writing code without chaining these then ables so let's take a look at that okay moving on from venables to async a weight so i'll put that up here as the focus a sync i could spell a weight there we go i won't get rid of all of this code but i'm going to show a couple of examples for sure and so i'm going to start out with an object defined in the global space and i'll have my users be the object and then we'll have a user list and that user list is going to equal a blank array at first at least and so there is our my user's object in the global space then i want to define a function now when we just define a function that is going to use async await we need to tell the function right at the beginning so we can say async function and then just name the function i'll call it my cool function and then we would have our function as we'd normally define it now i like to use arrow functions and so that looks just a little different than this syntax but you could see it this way i would have const mycool function and then equals async and then the arrow and so the only difference you've noticed from when uh we've defined arrow functions in the past is adding the async keyword there or traditionally with the my with the function keyword you put async before the function keyword so those are the two different ways of doing that now inside this function i'm going to define a response variable and that's going to be equal to what we get from fetch i'm going to request the same data from json placeholder but i'm going to use the await keyword and this is telling my code wait wait to get these results from the fetch that request that from the json placeholder api before doing what comes next so at this point we're going to wait for this to finish before we do the next thing and the next thing i can define as json oops json user data and i can set that equal to a weight once again because this json method also returns a promise so in both of these examples i'm awaiting a promise to resolve before i get that data and then i can just return the json user data or if i wanted to do something with that user data at this point like log it i could so i could say console.log json user data and we will actually have that data at that point to log because we are awaiting each of these promises to be fulfilled before we do the next thing within this function and it's an async function and then we of course need to call the function so we would say my cool function and we can call that now i haven't done anything with the my users object yet but i will here in just a minute let's go ahead and save this and you can see we once again get the 10 users returned as json now if we wanted to loop through those here we could like i did with the four each before but that just got rid of our thenables because we're just using these keywords async and a weight now to use the keyword await it must be within an async function and if we're going to call this function and do anything else with this data it of course needs to happen in order again and that is where we get into the next part where we could have a second function and that second function would also need to be async so let's say const and let's just call this another function now let's call func just so i don't use that word in there too much okay and then equals async once again so our another funk is an async function and this function can a wait for my cool function to complete because it's returning essentially data that is coming from promises that's an async function and then we could log whatever we get there so instead of logging that json user data within that function we can go ahead and log it within this function and we'll need to set this to data at least so we can call it something and we'll log that here in another func so instead of calling this function right here let's call another func here and see what we get and once again we get the same result so these are chained together in that regard and in this function we call my cool function and we await the results from this async function before we attempt to log the data that we get from it or work with it in any other way now the reason i have this my users object up here is because this is where mistakes can happen mistakes can be made and we'll take this same data and let's say we're going to go ahead with this second function in this data and instead of logging it we're going to say my users dot user list equals data because that's already an array that we've seen and that should work we would get that but let's say okay we've called all of this and we want to go ahead and do something with the user list in my users and let's just try to log it right here myusers.userlist let's see what we get we're not logging anything in these functions so this should be the only log statement we still get an empty array just like we defined it here now let's think about why this happened we waited for these functions to execute another func is waiting for my cool funk to get that data and we call another funk before we attempt to log to the console but here's the problem we need to remember that these promises are like hey i'm going to do my work but you go ahead and there's nothing about this console log statement that is waiting for anything else it is not within these functions it is not going to await anything so when this script executes sure these are defined and sure we call this function that calls the others but this function essentially has things inside of it that are saying hey javascript go ahead and do what you need to do and we'll get back to you and that is a reason that this is still empty we need to do it within this chain so if we wanted to go ahead and put this same log statement inside our function after we set it set the data here then we should probably get the result we expect because it's inside the function we've waited for these other things to complete then we have set the user list equal to the data and then we're logging the user list and i'll go ahead and i'll leave this console log statement here as well and let's see what we get and as expected we do get that array of 10 users for our user list but it only is delivered to the console after the empty array is delivered because we log this and this is actually happening first even though we called this function here so we have to kind of be aware of this chain of events that is happening and if we want to work with the data we're getting from an async function that is awaiting data from an api at another website and then of course we're calling that function within another async function we need to have our expectations lined up to where we're going to work with the data inside that function or we're going to pass that data to another function say at this point where this console log is on line 21 we can pass the data to another function and that function could then work with that data because it's only called after these things have completed but if we just have it out here as kind of a procedural top down code and we're not waiting on things to happen within a function just because we call this function another func doesn't mean this line of code is going to wait for those promises to resolve so does it seem straightforward so far or possibly clear as mud so let's look at some examples to hopefully clear this up and even if it does seem straightforward for you some examples couldn't hurt right so let's take a look at examples and we'll start out with what i would call a workflow function and this function is going to be called i'll just get rid of this object here we'll call this get all user emails and we'll make it an async function and we're going to work with fetch inside the function so much like we had in my cool function which i could maybe just get rid of this part and get rid of that i guess we'll have the response equal to the users being fetched from json placeholder and then we'll get the json user data from the response.json which is also returning that promise with await and then we'll do something else once we've got that user data instead of returning it right away or anything else we'll go ahead and define a user let's call it email array that'll work we'll set that equal to the json user data and then we'll use the higher order function map and we'll just go through for every user because that's the full user object that has all of their information we just want to return within this higher order function user dot email so this will give us a user email array when we're finished with that and then we can return that or log it to the console or whatever so let's just log it to the console and we'll have user email array is logged to the console i'll eliminate all of that and of course then we need to call this function so let's call get all user emails and let's see what we get we get an array full of 10 emails once again this seems straightforward we have an async function we await the response from json placeholder and once we get that that's a promise fulfilled we have the readable stream and so we take that response and use the json method on it and we await that promise to fulfill then we have the user data and then we take that json user data and run the map higher order function and create a new array that just has the user emails we just peeled that out of all that other user data and we call the function and it logs it to the console and it logs it to the console within the function let's go ahead and comment that out now what we've done in the past with traditional functions we can't do here we would go console log and attempt to get that information say returned if we had return user email array and this function would return that data and we would attempt to log it right here let's see what happens it's a promise pending this console log statement is not within the function and therefore it is not awaiting these promises to fulfill so it is still pending and that won't work we can call the function after we've defined it and within the function these things will happen in the order we expect them to it's an async function and we're using the await keyword to await the data we need before we filter it or map it create this new array we've waited to receive that data and so inside the function logging to the console will work we can return this data however it would be more likely passed to another function console log is a function we're actually logging that right there so let's say we had another function and in this function it would be well let's say it's doing something to the dom so we'll say post to to web page then we could pass in that user email or wow i can't type user email array and post a web page could do something with that let's define our post to web page function it's going to receive data as the perimeter and it is called within our async function but it is called after we have awaited this data already so we're not awaiting anything in this function it doesn't need to be async because we have already waited for this data to arrive we're calling the function after we've received the data we've already even worked with the data with our higher order map function here and so we can just do whatever within this function and it's not really an async a wait function it's just put into place within the get all user emails function after we have waited to receive this data so this one does not need to be async or a weight and after we define the post to web page function we need to go ahead and call get all user emails into action again because when we call this function it will call the post a webpage function at the bottom of its order user email array is not defined oh there we go i need to refer to that as data there we go and within the poster web page it is now logging the data to the console okay let's look at another example and this example is going to expand on fetch because fetch can receive a second parameter so second parameter of fetch and that is usually or is always i should say is a object and it has some settings that can be defined inside there so let's define this function and we'll call it get dad joke we'll start working with a different api it's an async function it's going to get a response from fetch and this will be from the url iconhazdadjoke.com but let's look at the second parameter of fetch it looks like i need to get rid of a couple of extra quotation marks so we'll put a comma and then we start to define our object and in this object we can define some properties one is the method now it will default to the get method but also uh you know there are other methods a form typically uses post for example and we can post data with fetch as well but in this example i'll just show the method property and we'll leave it set to get then there is a headers property this is a nested object and in this example we'll set accept and this is the type of data we plan to receive in return and that is application slash json data and then after that i think we're finished with the header and we're finished with the second parameter of fetch which i've highlighted there as you see mdn shows many other parameters and i will have a link to that in the description below this video okay so we've defined our fetch and we expect to await that response once again we get the response and instead of json user data this is going to be json joke data and we will await the response dot json as we have before and now instead of calling other functions or anything we were doing there we'll go ahead and eliminate that stuff and we'll add a console.log for the json joke data so we can see what that is let me save this and we'll call this function get dad joke call that into action and there you can see in the console we got a dad joke has a really weird id value and here's the joke and then we see the status and status is 200 which also would be response dot okay we could say if response dot okay do something but in this regard we're just bypassing that and getting the response turning into json data and then we log that so if we just want to log the joke instead of the full json data i guess i can leave that we just prefer to the property so i would say jsondata.joke and now we won't get the status we don't get the id we just get the joke and of course this is returning a random joke so every time i save it it's going to be a different dad joke you can see it takes just a few milliseconds or a second to get that joke returned from the server and there you see the best time on a clock is 6 30 hands down dad joke okay this api also can deliver data that is not json so let's think about that for a second and instead of json joke data we will switch this to text plane so we expect to get text plane notice i'm not changing anything else i'm not it's actually the root url which is a little different it's not a different endpoint by defining what type of data we accept from this api it's changing what they deliver so if we say text plain and then instead of json joke data i'm going to turn this to text joke data and instead of awaiting response.json there is actually a text method as well so we'll await the response dot text and now i'm just going to log the full text here and there we go and we get our joke what has ears but cannot hear a field of corn another dad joke for sure but that's an example of not really changing anything except the type of data we expect to receive and then the api responds differently okay let's switch this back to json or application json which is typically what we do want to receive from an api we like to work with json most of the time and we put our json joke data and we're awaiting response.json and let's go ahead and log the full object one more time and get a joke all right now i want to go ahead and copy this full object here and for our next example we're going to look at using post and that will also use the second parameter area of fetch as we did here with this joke api but this will actually post something instead of requesting data we're requesting to send new data to the api that can be recorded the api will send us a confirmation back so let's just call this function post data and we're going to send in a joke object and so i need to define this joke object and i'm going to go ahead and remove the status because it doesn't make much sense to send the status and that looks good it will probably it would look better if i put it on separate lines so we'd have that that and then there we go there's our joke object it has an id already and a joke and we'll have post data and it accepts a joke object parameter which remember this doesn't the parameter doesn't have to have the same name as whatever we've defined just when we call the function into action we'll actually pass in this name this is a placeholder when we define a function so post data accepts a joke object the response will be defined and we're going to send this to a different address i'll get that address quickly this is going to go to a test api that does let us test posting things and it's http bin.org and the endpoint we want is slash post now the method that we're going to use instead of get is post and then instead of accept we're going to tell the api what content type we are sending so this would be content dash type and we are going to send json so that's fine and now we need to specify what we're sending in the body parameter of this when we post it has a body parameter it's not sent as git does in the url as a parameter it's actually in a separate body parameter and we want to send json so we need to use json stringify and here we'll take that joke object that is the parameter we're defining in the function and we'll pass that in that looks good now we'll get a response and we expect to get a json response so that's what i will call this because we'll have a response that we get and we'll use the json method on it and at that point we can log the json response that we get and then we'll call this post data and we'll pass in our joke object let's see what response we get here is the response we got from the http [Music] dot bin.org slash post endpoint when we posted our data so we did successfully post that information to this endpoint now with every api just as we did with the dad jokes api and now this test api you want to go read the documentation for the api and see what they expect and see how they expect the data to be formatted and what headers they accept as you can see that was important with that dad jokes api now besides using the second parameter area of fetch and passing in this object like we have in the past two examples you can also pass data in through the url and that is of course with get because that is where get the get method uh sends data and not in a separate body property however you once again i need to i guess re-emphasize you need to go to those websites and check out the documentation because they'll have different endpoints and they're telling you how to specify the data in the url so you get the results that are expected let's look at a example of that and here we're going to request a joke so i will change this once again we don't need a joke object anymore and i'll set this function to request joke and in this example we'll have two parameters we'll put in a first name and a last name so we've got a request joke function that accepts a first name and a last name parameter and now we've got a response we don't need any of this now we're back to our basic fetch with just the url and in this url i'm going to use a template literal i'm just going to copy and paste to save a little bit of time but i will show you exactly what i'm talking about in this template literal i'm specifying the url and then you can see it starts to add parameters and you can always identify that in a url where the question mark starts and now here's the first parameter it's first name and that equals and i'm taking that first name that we're passing into the function and that's why i'm using a template literal with the back tick so i can insert that parameter right into the url and then you see the ampersand and that's what chains parameters together after the first one the question mark identifies where the first parameter in the url starts and then the ampersand lets you chain another parameter and there could be another ampersand and another parameter and so on and so here's the last name and we're also passing in the last name so in this example i'm actually using the internet chuck norris database and it's full of chuck norris jokes but we're passing in a first name and a last name that we want to insert into the joke instead of the name chuck norris so there's a response uh and then we'll take that and we'll get the json response as we have in other examples with the json method here and we await both of those again an async function and then let's just log the json response dot value and that is also important because at first i would just have to have logged json response and then taking a look at the object over here in the console to see what the properties were to know what i needed to log or it could be in the documentation of the api and you could find out that way i know i want to get the value from that response so instead of looking at the entire object we're just going to look at the value property and here i'm going to call request joke and instead of chuck norris let's put in clint eastwood and that's mostly because i can't spell arnold schwarzenegger i think i could spell arnold but schwarzenegger would probably be way off so let's try clint eastwood in here save that and here is the joke we get and we've got the id the joke and the categories so if we specifically wanted to just get the joke we would need jsonresponse.value dot joke there you go the truth will set you free unless clint eastwood has you in which case forget it buddy yeah let's change that here's a name i can spell bruce lee kind of a chuck norris action hero as well scientifically speaking it is impossible to charge bruce lee with obstruction of justice this is because even bruce lee cannot be in two places at the same time yeah some jokes are probably better than others now let's see what else we might do with this api because there are other parameters we can pass so besides the first name and the last name we can add on to the url another ampersand and then limit to equals and then this expects an array of categories and we're just going to give it the nerdy category we just want nerdy jokes the class object inherits from bruce lee ha that's better okay maybe let's try one more but these are just nerdy jokes bruce lee can overwrite a locked variable maybe not as good as the first one but i get where they're coming from okay now let's abstract all of this that we can into functions more like we would in an actual program so let's just say abstract into functions and we'll start breaking some of this down and the way we would start out is maybe we're pulling data from a form i'll put maybe from a form on the website something like that so we would have a function cost i'll say get data from form and we'll make this an arrow function that doesn't need any parameters but say it gets called into action based on the click of event click event of a button or possibly the submit event of a form something like that and we'll define a request object here so const request object equals and here we'll have first name bruce last name lee capital l there we go and then categories and now we'll have our array that has our nerdy category in it and that is our request object and we're going to return the request object so that would be our function that gets the data from the form based on the submit event or something like that is when it's called into action that's the first function the next one let's say const build request url and there we're going to pass in the request data that is needed to build that url and in the build url we're just going to return a template literal and let's look at this template literal that we have here and think about what we could do to modify that so it works in the function there we go so we don't want to just return it as is we want to change that just a little bit so this would be request data dot first name notice how we didn't have to pass in a larger number of parameters we're just passing in the object and by doing that we can then request each of these individual pieces of data from the object and that keeps our parameter count down as far as making that our function instead of having this long list of parameters so once again here we can say request data name the parameter and get that and then even where we have the limit to inside here we can change this array and inside the array we are inside this area we can say request data dot categories and it will insert the array that we already have in our object and we're returning that and that is the build request url function it's just going to return the url based on the object we pass in so that is another simple function as we would make in a program and then we'll have our request joke function and this will be just a little different now it won't take the first name and last name it's just going to accept a url and then notice this is an async function once again our others aren't but at this point this is an async function and this makes this a lot easier because instead of a weight fetch with this long url here we're just saying a weight fetch url that's nice and short easy to read then our json response is the same line as we've had previously and then from here we can get a joke array and we can have that set equal to jsonresponse dot value well when we think about getting an array we expect to get more than one joke so let's go back and look at this build request url we could just get one here so maybe we just want to say joke to begin with so i'll just say joke and then that is the response value or this would be a joke object because it's not just down to the joke yet if it was down to the joke we would say jsonresponse.value.joke so let's let's go ahead and do that and then we can just log the joke right here and that would be good enough there is there anything else we want to do oh yeah post joke to the page so instead of logging it right there actually what we want to do is call a function that would display the joke so i'll call that post joke to page and we're going to pass in the joke and now in our post joke to page function we'll accept a joke and here is where we will go ahead and just log to the console because we don't have a dom setup to work with right now now we won't call that request joke we have to call all of these functions into action see we've got our get data from form that might be called with an event listener and then we've got the build request url the request joke and the post joke to page but they're not pulled together in any fashion yet so we need kind of a procedural workflow function and i'll just put that here again procedural workflow function that's how i look at them that does all of these things now notice we do have an async function that needs to be in this procedural workflow so when we define this function we'll call it process joke request this is actually the function that would be called by an event listener instead of the get data from form say there was a click on the submit button or the submit value or this i guess just the submit event is triggered by pressing enter sometimes from a form it would call this function into action process joke request and it needs to be an async function because it's going to call an async function into action so here we'll have const request data and we'll set that equal to our get data from form function and then we'll const request url and we'll set that equal to build request url and of course that function needs the request data that we just defined and then we will await request joke and we'll pass in the request url and then we could just pretty much be done at that point or we could log finished just so we know we're done here in this example but this is the function or process joke request that would be called into action by an event in the dom and then all of these other things would fall into place based on that but we've broken out all of these things into functions so they could work one at a time and that happens in this procedural workflow function so let's pretend that something calls all of these into action now like a submit event and i'll just put process joke request and we'll call it here save that and here we get our joke bruce lee can write to an output stream and then we get finished and it looks a lot longer but this is how we would actually approach this in a program we would write individual functions for each of these things and abstracting this of course lets us build a different request url if we need to by getting different data and of course we wouldn't always assign bruce lee as the name possibly there's something else built into our program that would let us assign different names or pick different categories and then we end up requesting the joke and here is where we might work with the dom to actually post the joke to the page instead we're just logging it to the console and this procedural workflow function pulls it all together and you can see that i just called the function right here instead of actually setting it up with some button in the dom to do so but you need to remember this function needs to be async because we're using a weight when we call the request joke function and that request joke function is async which is why we can use a weight with it and it's saying let all of this finish before we do anything else hi i'm dave and i hope you enjoyed this tutorial remember to keep striving for daily progress instead of perfection subscribe to my channel and ring the bell to be alerted when i post new tutorials i'll see you next time
Info
Channel: Dave Gray
Views: 5,064
Rating: 4.9835391 out of 5
Keywords: callbacks promises async await, javascript fetch api explained, javascript, async await, callbacks, javascript promises, promises, async javascript, javascript tutorial, javascript callbacks, async, await, js promises, async await javascript, asynchronous javascript, javascript async await, async await js, javascript async, javascript promises explained, js async await, javascript await, fetch, fetch api, javascript fetch, javascript fetch api, fetch javascript, js fetch, api, apis
Id: VmQ6dHvnKIM
Channel Id: undefined
Length: 65min 4sec (3904 seconds)
Published: Tue Nov 10 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.