Understanding Promises and Async Await in JavaScript

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hello and welcome to swashbuckling with code i am jimmy cleveland and in this episode we are going to cover javascript promises and async await in javascript promises are a way to achieve asynchronous results which essentially means that they do not block the execution of code probably the most common example of that would be fetching data like say from an api and that would still allow your users to continue interacting with your app or your website because making an api fetch is one of the most common use cases of promises that's where we're going to start out we'll make a simple fetch and then we'll do something with the data such as logging it after that we'll get into the foundation of writing promises using the new constructor using promise.resolve and reject and also going through the various then and catch statements that you can chain onto promises after that i'll show you how to make some nested promise queries and we'll also show how to flatten those whenever we can to keep it nice and readable and composable when we're writing our promises finally we'll wrap it all up with a sink away example when our promise nesting gets a little bit too unwieldy hopefully that gives you a good idea of what the content structure is going to be so that you can use the time stamps to jump around wherever you need be depending on the level of knowledge you already have on promises but with that let's get into it [Music] for this video i'm going to be using a few different mediums to showcase the things that we're going to be delving into with promises because i think it's nice to have different ways of visualizing it and some of them do it better than others for one we're going to be using firefox in a couple different ways we'll be loading up an html document like normal it runs a script but i'm also going to be using the console because i like the way that it represents promises in their different states which you'll see in a moment i'll also be using quoca as a vs code extension and you'll see why i kind of like that when we get to that point i'll explain it so we're going to start in the firefox console here so the first thing i'll do of course is bump that up for you all the way as much as it can go that's actually max just so you know and then what we're actually going to do is use this nice little icon here that shows you this multi-line editor which i think used to be called a scratch pad it's a really nice feature that firefox has let's bring that over here since we'll use the whole real estate and what's cool about this is it actually lets you write out code and execute it whenever you want rather than executing one line at a time or as you like write one function it's a little bit akin to writing it in an editor which you'll see now for this first example rather than diving into the basics of promises and their various methods i want to start out with a very simple but common example of using promises so that you can kind of see what we're going to be building toward and you have something to base it on so in this case we're using the fetch function which is native to browsers nowadays in javascript but not in node and what we're doing is we're going to be making a fetch to this api which is the star wars api which is a nice little public api that you can hit to get some various data and you'll see in a moment and then we'll be doing these various things which we'll talk about in a little more detail but you can see that eventually we're going to console.log the response from this and then i'll go and create a variable and then i'll console log that so when we run this here you can see what happens it first shows the code that we created so don't worry about that and then these are the actual things that are running here and you'll see that we got created after fetch call this this variable was logged first before this log happened so for some that won't be too much of a surprise but for some of you it will so why is this happening this way that's because fetch or promises in general are a sort of asynchronous methodology in javascript which means that rather than running synchronously which means line by line they go off and they do something and then they report when they're done think of it that way so normally of course when we run our code each one executes one line after the other but in this case this goes off and does its thing and then these are able to continue on and that's why you get this first and then when that response comes back then you get it in this case we're just logging it but of course we could do various other things there's a really great video by philip roberts on the event loop if you're interested in learning a little bit more details about asynchronous javascript and kind of what's going on in the background and getting a better mental model in your head i really recommend that and i'll link that here another recommendation i have is by the always entertaining jake archibald on the event loop as well and it's a really in-depth detailed video about set timeout and promises and all sorts of good stuff like that that i really recommend checking out if you're trying to get a good mental model on what's going on in javascript with asynchronous behavior so let's actually start with the mdn docs with promise to get into you know how the different methods and states of understanding it i'm not going to be you know thoroughly going through all this just using it as a reference and i highly recommend you know browsing through it or reading it whenever you get a chance because it definitely is really well written so for promises this is the most important part to start with i think is that there are these three states there's this pending fulfilled and rejected and so what we're going to try and do is showcase that you'll also see that there are these general methods and i'm actually going to start with promise.resolve just to kind of see that so when you write promise you can actually just call it like this and say resolve and when you do that you'll see i'm so i'm going to press ctrl enter here and that will run the code you can also click this little button if you're using fire firefox and following along and here you'll see that we have the state fulfilled with no value right so what if we just put a value in real quick and say value and some other stuff just you know no reason i refresh just to rerun it here and clear that and here you can see that we have the same thing but now we have this value stored in here this is something i really like about chrome and firefox is how they represent promises when you run them they show you this promise object and the state and the value of it so there's our first state we have fulfilled right so that was one of them fulfilled and that's when we just resolve it hopefully you'll understand that a little bit better once we start building our own promises but that's just a fire off of resolve right away so what if we fire the reject method what happens and we'll say go away all right i'm gonna refresh that just so we don't have any noise when i run this so the first thing you'll notice here is that we have this error right and that's always going to stand out to you first you can actually ignore that for now we will explain that in a moment just an uncaught error but then we get this promise object state and it's rejected and notice that it's not value it's reason and the reason is go away so we've got uh rejected here we've got our fulfilled so how do we get a pending state well these are actually evaluating like instantly here so let's try to do something like this well let's use the promise constructor to demo this real quick so i'm going to say new promise you can call it like that and then what it takes is a callback here that will give you a resolve and a reject method so we're going to just accept the resolve for now and then we'll just use a quick arrow function and what we'll do inside here is we'll use a set timeout and we'll just have a function in that set timeout that calls resolve so that we can pass it a value and say i waited and then after that of course we will pass in milliseconds here and let's just do like one thousand so we have a second we're going to wait a second here and then see what happens so what we're doing here is we're showing that we can actually by waiting to resolve this thing once this promise is created here the promise as soon as it's printed out as it's run is in a pending state which is our final state here and that will be a little bit more normal when you're using promises so let's say that you're making an api request it's going to be in the pending state until that api request comes back to you with either an error or the data that you wished for in which case it will be fulfilled or rejected now you'll notice that we didn't get any sort of log or anything like that from i waited right and that's because all we're really doing is calling that resolve function which is going to give us something that we can run a then method on so let me actually store this variable real quick and say my promise equals we'll make this new promise so if i just try to access my promise here and let's refresh and run that you'll see that we're still just going to get this state pending what happens if i console.log my promise okay same thing here right just getting this promise state pending this time it's actually logged here but what we can do is write my promise dot them now the promises is doing this sort of iou behavior which is saying like whenever i am ready then i will pass you back this thing so in this case we'll say dot then and what we'll get back with the then method is a some sort of response is what it's commonly referred to and with that response we can do whatever we want so let's console.log the response here run that code and you can see after a second it says i waited now something interesting we can do here is that we can on a new line here let's say uh i want to console.log my promise okay so we're saying uh once this dot then fires and it should be in a fulfilled state after we log out our weighted i waited can't talk run that again you'll see i waited and then the state is fulfilled so here you can see a promise going through these different states going from pending to fulfilled once it's completed so a promise also takes or gives i should say a reject method here the callback takes it and from here we could after a set timeout just call reject so reload want to run this let's see what happens notice that we got uncaught in promise i waited we don't actually get this state right here and that's because when you get a rejection the then method actually isn't going to return it in the first callback here this is a little bit confusing of syntax to look at but let's see if this this is the whole first argument of it and then the second argument is what i'm going to put is let's say error or something like that and then here what i'll do is all console.log respon or error in this case and then also i'll do console.log my promise reload i'll run this and here you now you can see we got the i weighted value still that was the error that was passed but this time it says the state was rejected and that's the reason as i waited so you could you know in this instance do console.error here see that so you can kind of just put your own console error however you want to handle it and the point here is that rather than actually throwing an error and halting your execution you might want to do something else you might want to have a fallback state you might want to send it off to your logger if you happen to have a logging service etc etc the choice is up to you i know the syntax a little bit confusing this is the first argument and then this is the second argument that it takes now i don't commonly see people use it this way what you can actually do instead of this let's take this right here and cut this out is you can chain on and i like formatting it like this because i think it makes a little bit easier to read oops style that back here sorry i like to chain it like this so we can actually continue to chain one method after another you know just like you know map filter reduce or anything like that but we can do a catch block here so in this case i'll paste that code from before oh goodness forgive me this is very difficult i am not normally going to be editing inside of the browser like this you know i'd be using my ide but i'll struggle through it for your sake so here now we have this catch block which is really interesting and so what this is going to do is catch whatever this error is and then we can do whatever we want the normal way that we did but instead of doing it in this you know more confusing harder to read syntax where it takes these two functions we can just do it in one catch you can see we get the same result here right now we don't need this then here just to be clear we could just go straight to the catch i don't know why you would ever do this but we could the point is that this is this really neat format that a promise when it gives you the sort of iou back depending on the state it will go through these various different chains so to take it a step further and to show you the generic kind of model here that you want to be using what you can actually do is from this then you can return something and that is going to be received here so let's say i'm going to return even though i'm logging it out i'm going to return the response okay and what that will allow you to do let's say we'll go back to this being a resolve is chain onto it further from that now i'm going to not do that first just to show you that i will get the i weighted response which is this console log here and then we're logging out the the promise being fulfilled and then we return but it doesn't do anything after that that's because the catch block is not going to be fired because it's not an error right but i could do another then and i can name that whatever i want i can change the name or i keep the same since you know we're at the same scope level here goodness and then what i'll do here is i'll console.log the response one more time and maybe to make this a little bit more clear we'll say first then and then we'll say second then and then i guess let's just put this here we'll leave that as an error because we know what it is i'll return that and i'll run it oh whoops mr comma rerun that again okay first then i really should put a colon here make that a little more separate and easier to read but first then i waited second then i waited right now this seems pretty pointless at this point and it should but you can see it's just to illustrate that you can continue to pass this down by returning from our promise anything that a promise returns will be then-able or you can run then on on the next step if i were to return an error here let's say or just throw an error how about that so throw new error it will get first then i waited so this actually got hit but then i threw an error and the catch block caught it here in fact let me add catch block it's not really a block i guess see that just to be sure so that you know uh so it's skipping this step right here and i'm going to show that i think it's a little easier to understand or kind of see going on uh in my vs code just one second what i want to show here is that to end it off if we go back to the return we can actually change our values so we got that response right but there's nothing stopping us from adding on to that or changing it or or let's let's completely flip it up here let's return an object that i'm just going to make on the fly and i'll say you know value is response response let's not make that a string and then something i added this okay so uh right here we have this first then right here got called then we'll see here that the promise uh fulfilled yadda yadda that's this log right here but then the second then that is right here okay that logged this has this object which has something i added this and the value i waited so that's this original value i waited and we don't have to return that i mean honestly we could return anything we want ignored the response right last example here just to show that you know the second then ignored the response so you can do whatever you want in these promise chains you can just keep returning and then all that stuff let's take a look at that in a different view uh to kind of show how it bypasses things so in this case in my editor um i've got just a simple index.js here that i'm going to be writing for just a moment but what i'll do let me close that so we've got full real estate here is i'm going to start quoca on this start on current file and if you're not familiar with quoca it's a very nice little extension it essentially continuously runs the code that you write in that file and gives you this nice way to print it out you know seeing is probably better than being talked at so here we go so i'm going to write a const and i'm going to call this success promise and then we're going to make that equal to a new promise and we'll do the same format as before we'll pass it a resolve and in this case i don't need to get reject off of it so i'll just ignore that and then here what i'll do is i'll just call resolve and of course you know normally when you're making a promise if you're promising buying things as it's commonly called you could be doing all sorts of things in here a common thing is to use set out to cause a delay after so much time etc etc but you know let's just stick with the basics here so we've got this resolve and we'll say uh you know resolved value something like that now you can see on the left here i've got these little green boxes that's quoca letting me know my code is actually running and you'll see that in just a moment here some differences okay so next let's make a new variable here failure promise that's going to equal a new promise in this case for our callback function i'm just going to put an underscore since i'm not using that variable and then i'll do reject we are going to use that and then let's just call reject this time i'll do rejected value okay so this is where it gets interesting so what we'll do is we're going to call success promise and you can see that quoca prints out this then resolved value which is really interesting so what they do is they go ahead and even though you're not calling the dot then method on it they're saying after you run it then you'll get this it's really neat what's kind of interesting is if you do failure promise they'll put a catch rejected value so they'll say well this is this would only print out in the catch block that's what you're going to get as rejected value let's make that reject it so we don't miss it so let's go back to the success promise here we can do here is we can then chain off of this and so let's do our value or response or whatever you want to call this it doesn't matter for this first level i will say console.log the val and you can see that we get this resolved value it's the actual one it doesn't say then at this point but i can also in quoca just print it out by writing it there and then i will return that value okay i'm going to write another dot then here i'm just going to chain it along you know that's weird to you it's just the same as that calling it afterward back and put it on a new line we'll do one more here and then what we'll say is um we'll call it val again do the same thing make sure what we have the vowel is and then we will return uh i'll set this up in one second let's do a vowel one more time and then finally we'll do a catch block in this cache block we'll call it an error and then here's where we will console.error error okay now you'll notice that this little white block appears here which is kind of interesting this y block is saying that this code didn't run at all and that's because we don't have any errors at this point if we were to switch this over to failure promise you'll see that we get the rejected value and none of these ran but this one did this is a really nice thing about quoca that i like because it shows things that were skipped so let's go back to the success promise now check this out what if i return from here failure promise isn't that interesting i don't know why it's saying reference error oh it hasn't like updated yet is why if i save i'll do x e sometimes it gets stuck like that don't worry about that so here you can see that this first block ran but then i actually returned a whole promise not just the value from that promise isn't that interesting so i returned a promise that called reject or called resolve and because i did that it was caught in the catch block so if i do success promise you can see once again this one will run it won't run the catch and then finally if i return to success promise again it's not going to do the catch block it's just going to you know you basically have kind of left it open to be bend on one more time but you're not doing anything with it but if i ever do failure promise now all of these code lines execute let's go back over that briefly one more time here what happens here so we start with the success promise that we make a new promise and then we just immediately call resolve we don't do anything because it's kind of a useless promise this point but you know it's for example purposes then we also had this failure promise we did the same thing but we just did reject we start with the success promise and then we say dot then so when you're done resolving that promise which in this case is instantly well instantly in an ace instantly in an asynchronous way to be clear so then we're going to get a value we log that value out and cocoa nice and it just puts it right here for us and then we return the success promise and that success promise is a promise that resolves and so since you have a promise that resolved you can then move on to the then and then finally we return the failure promise which triggers this catch and as you saw if you put this at any point it'll go and trigger that catch so you can return values from the promise and keep bending on them modify them whatever you like as you've seen or you can return a promise itself and that will be really important to understand in an upcoming segment here where i'm going to show nested promise fetching and how you can flatten that out a little bit because a lot of people seem to not realize that and they just jump straight to a sync await so now that we've gone over the basics of writing your own promises and creating them and all that such and how you chain them with venables let's come back to making a fetch request because that's i think the most practical and common example so we're going to start our fetch and you could use axios i if it kind of depends for me fetch is nice because it immediately runs in the browser you don't have to install any packages and that's why i'm going to use it here if i have a larger scale project i'd probably use something like axios because of the ability to set defaults and not have to set your content headers and all that good stuff just so you know but we'll stick with fetch here um it's nice to just be able to reach for natively and so what i'm going to do is i'm going to do https colon swappy.dev api and then you can go to people again and in this case we'll still just do we'll start with one okay so we're gonna get that fetch working and then um it's just kind of common to format it by putting it on the next line because it makes it a little easier to read through as a synchronous sequence of steps so we'll say we're going to get a response back right and that response this is kind of an odd thing about fetch compared to like something like axios is that you have a bunch of different ways that you can kind of convert the data the most common that you're going to do for like a json api is just call this json method and so that also is going to return this value that you then want to then on okay and in this case we could write response again or we could make it like maybe a little bit more readable and say person so we got a person back and then here let's console.log for now person why do you format this way okay let's run that you saw that we got the state pending this was just our code and we're back where we were before where we have all this nice data for luke skywalker right now to show a kind of a silly use case but how you could do something besides console.log let's scroll this over here if i go to my inspector what i've done is i've made this little pre-tag here that has an id of result block so let's go back to our code and what i'll do is i'll just simply grab that so i'll say const free block equals or we could do pre-tag whatever document dot query selector and then that's an id in this case and so i'll do pre block oops can't type now i'll do the space just to make that clear and then here instead of logging this what i could do is say pre-block dot inner text equals and we'll do json.stringify we'll take the person and dump that there we'll do the standard null and then two space indents oh we got an error what was that probably from pre-block is null oh don't be silly jimmy it's what do we do that as result block result block apologize for that oh we're all over the place ah it's refresh so we'll run this again and i'll just lengthen this just for a moment so you can kind of read it here so yeah we're going to uh call it once we get the data back turn it into json it's actually just called the json method so we're turning it into an object here but then we're going to set the inner html here so if i run that you can see that i'm just dumping it on the page here and if i didn't put this like null into it would just be one long string all the way across it wouldn't format it just so you know so really the only reason i've done this it's not much different than logging it out it's just to show you that you know you could do whatever action you want in here and in many situations you might just dump some data or you might you know have a an object up here that you're you know assigning that data to you're causing some sort of side effect i guess you could think of it as now let's take this one step further here because i think that's kind of interesting is what what we get from this data you'll see that the way this api works is that a lot of these values are sort of static but this one is a url in order to hit isn't that interesting and that's because homeworld has all its own data and rather than you know like either it's it's just a way to write an api where you can have these kind of just like variables like dynamic endpoints that it hits you could obviously make your back end like go and grab all that data but in this case the way they've made this api is to just grab kind of the minimum of what you need and then you can go and grab more if you need that so let's take this line right here and we'll cut that out just for now so what we want to do is we say okay well we've got our our person we've got luke but i want to know his homeworld okay all right well what will we do here we kind of just need to run another fetch we can't really run it outside of this because we need to go get the person first and that will give us the data that we need to get the next thing you'll run into the situation quite often uh when you're doing any sort of complex queries or anything like that where you'll get you'll do some sort of promise and then based on the results of that you need to take that data and do something else so that's what we'll do next here so i'm going to fetch but what's interesting about this is i can just say person dot homeworld because this is the person we got back and then we're just going to go to that homeworld we're going to do the same song and dance again here let's say we do a dot then and it's really common to do this res.json just to make it shorter most people will do this with res i'm kind of a stickler typically because response and resolve and some of those other things are similar so i like to write out the whole word but of course if you want to be succinct go ahead i prefer to be a little more declarative typically but just to show a common pattern since you'll see it a lot so there you go res res.json and then we'll say okay well after that then i want to let's say we're going to have homeworld at that point and then we can do the thing that we wanted to do before which is this pre-interblock but we'll swap that out with homeworld okay now we're getting a little bit crammed here but i think you get the idea so let's run that now just refreshing and notice that now it prints out the homeworld that luke is from tatooine so we've simply just nested these different fetches now i hope you can see at this point how nonsensical this could get and if you happen to been around in the time of call back you know call back hell and christmas jerry of death and all those various terms that's got an eerily similar vibe you're going to keep nesting if you need to keep doing things it might not even be api fetches it might just be general data stuff and it's going to get messier messier messier and let's say what uh you know the next thing we want to do is you know get these residents or get the first film or something like that you know you're going to have one more fetch there so what we actually can do we learned this earlier that you can return not only the value but a promise and from that promise you can do it then so what if instead of kind of nesting it like so and doing this pre-block here we were to say return this fetch and of course you could keep the then here i'm personally a fan of breaking all of my lens into their own thing and i'm going to do it that way just to show you so here this is the end of this sequence here so we've got that and so that's this then here oh i missed something uh we need that that's this oopsy daisy so let's get that yeah that looks better oh braces and parens how you get me so then we'll do this and we've got that oh my goodness formatting and i'll just bring this here just to give you a little bit more just real estate so you can see it there you go okay normally if you're in a normal size editor this is closer to what it would look like but obviously we're all zoomed in so do you think this is going to work hmm it does because we simply learned that we can return that promise and so rather than nesting it you can keep this nice and flat and sort of instructional so you can see now because we're using fetch axios would be a little bit cleaner because you wouldn't have to do this extra json step but regardless you can see how if you're doing a bunch of promise stuff you can you can read it as a sequence of steps which is really nice you go and you fetch the thing then you do this then you do this you're going to get that data back from a promise then you can move on and process that as json and then you have the homeworld and you can do whatever you want we can actually make this a little bit easier nicer because we we could keep this all fancy for doing simple stuff like this and uh use an implicit return and then we'll just reload just to show that that still works and then it's even a little bit cleaner now it's not always going to look this nice but a lot of times it actually will if you're doing pretty simple operations that you can just return you remember one value just returns to the next returns to the next the same ideas like mapping filter reducing all that good stuff that you typically learn and declarative programming and all that good stuff so if you can you want to be flattening your promises as much as possible it just makes them a lot easier to read not have to deal with you know the best the nested christmas tree of death nonsense but i'll throw in a little disclaimer here sometimes you need to do a little bit more in this case we're just getting back home world right at the end but what if we actually wanted luke with his homeworld attached to him okay right now we sort of have this function we've got get person person's home and it takes an id let's say which is kind of funny so then we could say const get a person's home is equal to fetch this thing and then we'll turn this into an interpolated string and then that will make it to where we can do uh you know braces here id and then i'll go back here and i'll make this an actual function that takes id of course ah formatting okay so now we have kind of the same thing you know make sure it runs so yes we have get person's home and that's great and that's how you can kind of make this general use functionality of this but what if you just wanted get person you know with home you probably wouldn't say with home but you want to get more data for them well in this case you're kind of in a tricky situation because when you go and you fetch this homeworld and you get that json back at this point you don't have access to person it's in this function scope here so what do you do well you could do something like this where you say const person equals let's say you know by default it'll just be an empty object okay and then on this step right here we would actually have to put a brace back here and say person is equal oh well we've got a scope let's say person data to make it not confusing person data is equal to person at this point and then we're going to do that fetch still but now we have to manually return it retron it classic and then that will be here we'll have a brace so we'll assign person there and then finally when we get the home world what we'll do is we'll say person data dot homeworld so we'll replace what we had before which was just the url we'll set that equal to homeworld and then when we json stringify we'll just do person you think that'll work oh it's not get person's home anymore you silly goose get person person make it make sense oh and i can't assign that of course i was thinking you know i have an object and i was going to mutate it but let's just do this why is person not defined oh the person data here we are making a lot of mistakes i'm sorry there we go goodness okay so now this does work we have luke we got his homeworld we dumped all of that data you know we haven't gone and gotten all these things but you can see it then moves on to all various other data so this is a way that you would kind of accomplish this it's kind of it's all right i don't really like the whole mutating outside of this i like the way that we had it before but if you really do you know need that previous data you're in a kind of tricky situation there are little what i would call them little hacks little uh tricks around like returning a promise that you could like make as an array uh of the fetch and then the person and do some different fancy stuff with that but it's a little bit confusing to do it that way if you need to do something like that i would do it this way but this does bring us into a pretty good use case for example for when a sync await can be pretty nice so with what we have right now what we could actually do is make get person an async function so we could just say async here if you're not familiar with this just hold on so that i'm just going to put some braces around that function here now with async what you can do is you can make a variable and let's say person we'll call it that and we're going to await something and you can only use this await keyword if you have async here and then what we'll await is actually this fetch right here to come back and we can still chain this onto it if we want um but it's a little bit kind of confusing so let's do it like that and then from here we can console.log what is person now normally we wouldn't be able to do this outside then right but what this allows us to do is run our code sort of synchronously to where it will do this thing and then it'll stop here before it can do this next thing this function itself is asynchronous but within it you can run everything line by line and sometimes it's a little bit easier to reason about okay so we'll do that and for now let's comment this part out and let's say that that's all we do is we just call that and we won't need this either okay now oh goodness here you can see that we did indeed get luke back at this point okay bring this back over here for just a moment so we got our luke data back um and you can see that that works pretty well console log normally you know if we were to put it outside of it wouldn't have been able to access that data but in this case it can and so that allows us to keep moving on with the next step in a normal synchronous manner so now we'll say okay well you know go get me the home world we'll say wait and that's where we'll comment this back in for just a moment and we'll say okay we have this then person blah blah blah blah we just want to do this part right fetch the homeworld homeworld await fetch get rid of this uh we will need this you could also do each of these one by one if you wanted to but i think that kind of creates too much noise and then finally on this last step we'll have a home world so we don't need to do this then home world we can actually just delete this block here we would do something like this and so we would just say okay well person oops we don't need person data anymore sorry and we'll make that home world is just equal to the result homeworld we're here we'll do this and there you go we don't need this variable anymore okay so let's reload and run this and you can see that it still works now so we've got our luke and we have our homeworld and we've built this whole person object with luke and the homeworld on it so this is kind of the value of a sink away and some people uh would would say that you just pretty much always should use a sync weight because it's just a little bit easier to reason about that code i think that that's a valuable argument i could see that you know just kind of using it one way all the time depending on your environment it's possible that you might not be able to but it's you know most environments nowadays do have a sink away and so you'll be fine with that sometimes if it's a really simple promise i don't mind just writing a normal promise personally it just kind of depends on the code base but there you have it you might find this a lot more easy oops sorry to uh you know read and reason about you go and you get the person it actually should be probably called print person right since we print it here but you go get this person you have this async operation you go and fetch the person and you store it in person you go and fetch the homeworld and you store it in homeworld and then you just change this little property on it do a little mutation dance and then you go ahead and do your side effect or whatever you're doing now what happens if we wanted to to keep this as a get person but uh and not a print person and we want to make a separate function as i think you should to print person so let's say const print person and then in this case for now let's just say oh well this is just a function that maybe it takes a person right we run this block right here well that means that we would have to return from this person so get person in this case print person that's a lot of same person what we could do here is we could say let's call print person with the value get person if you don't like that you could store it in a variable first of course and see how that works let's run that object interesting right okay well what happened what if we cancel log person here and see what we get we got a promise with the state of pending if you don't believe me i'll put person just to make it more clear look at that and then it got fulfilled once i opened it isn't that funny watch this this is an interesting thing that chrome does so when this is printed the status is pending but when you like look into it's kind of like a schrodinger's cat thing when you look into the object it will actually update with what the values are this could be really confusing sometimes if you're looking at objects that do mutation or change them afterward think that your thing did write or didn't write you get the idea it's pretty confusing but you can see that we still just have this promise object and we can't write that promise object we don't have the data so what do we do here because you know i thought that we just asynchronously got everything a return person this is kind of a gotcha here because you know when you wrote this async thing like i said this function is asynchronous it didn't just turn javascript everywhere into synchronously writing and actually that would be really confusing if it did it has made this you can think of it just as returning this promise anything that's going to be returned from here is still going to be a promise because it needs to be treated asynchronously okay so what we would just need to do is we would need to do something like person dot then data let's say and then we'll put this block here we're doing a dance we don't need this line anymore right and then we'd have to change the data because that's what we changed it to get back let's run that oh it works cool so even though we're using this you know async await thing and a lot of times with the sync await you won't even see these then statements in here you know it looks something like this and people get pretty confused understandably that you know you could write everything in a sort of non-promising way without lens and such but what they might not realize is that you know in the end you've still got to handle it with this then statement however you're doing it now you might be thinking well can't we just a sync await here yep sure you could uh you could say const theta equals weight person and get rid of this line here and get rid of this line here reload rerun and that works right you got this promise back you don't need to then at this point because you just got this promise back and you're just awaiting it i think that shows off kind of the sync away syntax fairly well i hope so if you wanted to you could go sink away all the way but i wanted to show you that it is just kind of obscuring it and a lot of people jump right to sync a weight because they're not used to doing a lot of heavy callback or promise things without really understanding the inner workings and it can get pretty confusing you know like you you could be totally coding in a vacuum of a sink away and just be writing you know this block right here and maybe the the package or whatever you're using is doing this type of stuff for you or i should go back to the like the promised then type stuff for you and you don't really know that you need to do that or that you can't access this out here in the root you know you can't go and store that variable here you know you can't do something like this let person at the root you know let's say we start with this object and then here um i said person data last time let's make that less confusing person data blah blah blah blah and let let's say that um you know print person you wanted to be a bad person and use a bunch of crazy side effects stuff well you could say that print person doesn't take anything and maybe it reads it just does this simple thing person data we don't need to return here instead we'll just say person data equals person at this point right so we've gone and we've done all our mutations on person and then we're just going to say this is person data now we obviously could have just reassigned this but whatever let's rerun that you're still going to get that object this is what i'm getting at like you you can't do that you need to handle that promise that venable in some way and that's what a sink await is doing for you hopefully that kind of clears that up i know it can be a bit confusing if you're not used to it but i just wanted to show that that let's go back all the way here you need to do something to this effect i think that'll be good enough let's get that running again beautiful now at this point we have covered quite a bit and i would love to show promise.all or all these other different various methods that are really cool if you look at these methods there's a bunch of neat ones that are kind of fun to dive into and understand that well in this for a real quick example this residence you know we would have to go get a bunch of different things it's not just one fetch and so how would we wait for all of them to complete or maybe the first one to complete or something like that that's what those kind of methods are for and you can return that all as a promise that comes back as an array but that would definitely add on to the length of this video considerably and so i'm going to call it here and if people have requests for going over those methods then i'll consider doing a video of that in the future this video was a pretty tough one for me to put together uh just trying to decide on what the right way to display promises and kind of think about them and how much depth i should go into async and all that stuff so i apologize if i didn't really do as good of a succinct example but as usual i hope that this was a little bit informative for you and helped level you up a bit into getting a better grasp or concept or maybe you're just brand new to promises kind of getting your head around the idea of them and how you would commonly use them for some basic scenarios but if i did not do a very good job go ahead and let me know in the comments and i will do my best to improve from that feedback thank you and i hope to see you next time
Info
Channel: Swashbuckling with Code
Views: 1,119
Rating: 4.9487181 out of 5
Keywords:
Id: 2Ur9X4tUI9Y
Channel Id: undefined
Length: 48min 59sec (2939 seconds)
Published: Mon Mar 22 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.