16.11: Promises Part 1 - Topics of JavaScript/ES6

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hello I have a promise to make sure by the end of this video I am hopeful that you and I together will understand what the how this promises thing is in JavaScript because me I'm a person who programs in JavaScript with callbacks but there has been for quite a while something called a promise in JavaScript and it used to be something that was part of certain libraries that you could import and add to your code now as of I think es6 which is yes 2015 whatever as of a more recent version of JavaScript promises are something native to how JavaScript works so I hope this video will answer the question for myself as well as you why should you care about this what is a promise and how do you make use of a promise so the demonstration so I have a JavaScript program already running it and I think a good way to demonstrate this is to look at making requests for data from api's so I am making a request for a random word from the word Nick API and then I am asking the giffy API for a gif Assoc of that word so if i refresh this page there we go i refresh this page again there we go so this is the demonstration I'm going to use now that at present the code for this is using the p5.js library with callbacks there are no promises involved there's a load JSON function that passes in the URL to a particular API it has a callback for when the data is ready then I get that data and then I go I ask load JSON again with another URL and then I who then I have another callback oh my goodness so here's the thing a callback really makes sense for this idea of an event right when the mouse is pressed trigger this function it's an event but if I want to sequence asynchronous things that happen in my program meaning I'm making all these API requests I'm asking for this I'm asking for this and then when this comes back I want to do this callbacks can get very unwieldy and you can actually find yourself living in what's known as sound effects please call back hell so I'm going to show you right now and call back hell [Music] now I've written this in a weird sort of way where I call low JSON okay that's just way too distracting where I call low JSON and then but you might be you might imagine that you use anonymous functions so when I call low JSON instead of having this separate you got data function I'm gonna take this up here and I'm gonna put this in here why is this so and then I'm going to I don't need it to be a name I'm just gonna pass the call back in here directly okay so this is perfectly normal to do ah but then when this one when I then go to the giffy API then I'm gonna I need this next anonymous function and I need that to go in here I don't want to name it anymore it's an anonymous function and there we go so now let's refresh this and it still works homeward bound oh there is no what's great about this is this is going to trigger an error sometimes when it can't find an image and I'm gonna need that with promises I'm need to figure out of handling errors so look at this this isn't even that bad this is fur but but look how this is just not sustainable first of all I don't like how much room I have here this is like absolutely not sustainable I won't up load JSON have this callback then load is none of this callback this King I could just keep going with this and all of a sudden you can see my code just gets indented and indented and indented more this isn't good could there be something better I don't know I don't know really if it's better or not but there is something and that something is called a promise a promise is an object so the idea of in so let's say so we have this load JSON function which expects a URL and then a callback here's another reason why we could get stuck in callback hell we might need multiple callbacks or different things like an error callback and then or then our code is even more unwieldy because then we have these sequences and we have different things for the success callback so this is what our code looks like with a callback now p5 at present doesn't support promises but if it did instead I could say something like this let promised equal lo JSON URL so the idea is instead of passing a function a callback you ask a function for a promise so because the p5 GS library doesn't support promises and I am here to teach or learn which one I'm not sure yet about promises I'm going to instead use a function called fetch which is a function native to javascript in the browser that supports promises so this gives me a promise once I have that promise I have it as an object and I can do all sorts of things with it but the idea of a promise it's an object that can be in a certain state so the possible states are it can be pending right this is while I'm waiting to get the data back from the API it can be fulfilled which means it's it's been successfully resolved I have the results back from the API or it can be rejected meaning some error has happened so if I have this object the idea is that I can just check this object to say wait hey object what pay promise everything's fine I just dropped the top of the marker I have this problem I have this promise I promise you promise me something are you still pending I'm waiting for you to finish promise are you pending and then I could say like hey were you rejected were you filled and then give me the stuff back but here's the thing if I do this I actually don't need to query the promise continuously I can use something called then and/or catch then is a function that receives a function to be execute it's kind of like a call pack when it has been fulfilled and catch receives a function to be executed when it has been if and when it has been rejected and there's actually if we go back if we go to the Mozilla JavaScript documentation page there's a nice diagram so this idea of a promise it's pending you can see all this stuff that happens but in the end there's just a then or a catch so this is the basic idea so what I'm gonna do now is I'm gonna start to rewrite that code using promises now I should be explicit about a couple things number one is I am NOT creating I can write code that creates promises I can use them and I'm gonna get to that but I'm not doing that right now what I am doing is using somebody else's function that returns a promise so I need to get to creating your own promises and I'm gonna make lots of promises and then the other thing is I need to like to see does this willy help us does this really make our code easier to follow and so let's just sort of see so let's let's go back so first of all let me just show you where this function called fetch is coming from so this is the fetch function and basically fetch is just a function that you give it a URL and it fetches the stuff from that URL and gives you a promise back so I am going to I'm going to comment this out and I'm gonna say let promise equals fetch word Nick API and then I'm gonna say console.log promise so I so let's take a look and see what this is look at that and at the moment that promise is pending look the promise is pending yeah here's the thing let me make I'm gonna do something very silly which is actually let me do let me do this in let's do another one here let P equal Fett let's do this again just in the console and let's look at that it's resolved like a few moments later it's resolved right so at the next line of code so I could do something crazy like while promise is not resolved wait wait wait wait wait wait but that would be like blocking code the point of a promise is to handle asynchronous things my program is going to keep going but behind the scenes it's going to be waiting for that data and the way I do that I don't think way too much time to get to this is with the ven function so watch this if I say promise then and then I put got data in here and this is nobody would ever write JavaScript like this I'm just doing this in kind of a crazy way and then I will condense it down and then I write my got data function let's run this and take a look at this looks a little weird let's run this now so I got oh yeah I forgot all this is great I forgot the fetch function has some weird properties which is going to cause us a bit of a problem which is why we need promises so look at this I actually so you can see I got the results back but actually the results have to be converted into a format that I can use so all right so first of all so this is the idea right and if there was an error I could say promise catch got error and I could say console.log error all right so now let's make it have an error let's like mess up the URL by accident and we can see I got an error there type error failed to fetch so you can see this is the idea I get a promise I can give it a function to with then for when it's successful and I can give it a function for when there's an error I forgot to mention I'm gonna start probably using the JavaScript arrow syntax in the course of looking at promises because it's really helpful and it's many ways necessary for working with them effectively so if you haven't already watched my video or somebody else's video or tutorial about the JavaScript arrow notation which is this notation I would suggest you pause and go ahead and watch that and come back okay so how would somebody really write this code well most likely you don't need to create this variable call to promise and then say dot then really most likely what you're gonna see is just saying fetch and this is called chaining almost everything in JavaScript is chained meaning I'm gonna do this function and chain it with the next thing I can say dot then got data dot catch got error so this is more likely how you're gonna see it written and let's just see do we still get that we still get that error and then if I fix it now we can see we've got that response back correctly okay now how would I really see this most likely I would see this with the use of anonymous functions so this whole thing would end up in here without a name and then this whole thing would end up in here also without a name this is starting to maybe look a little better and you might even see people do this so thes here's the thing there's gonna be a lot of sequencing and what promises are gonna allow me to do is really nicely say dot ven-ven then dot then so I can create this sequence of callbacks more easily now here's the thing if I want to clean this up even a little bit more I might want to use the arrow syntax and once I use the arrow syntax if I just have one line of code I can simplify this let me make sure I have this right and then I can do this did I stop talking I have to concentrate and this doesn't need a semicolon whoa I made this confusing but let's just do my best here all right so let's just make sure this still works and then let's look look at it again okay it's still working so look at this business starting to look kind of nice it's confusing this is not for the this is not for your first day of programming but I now have fetch which returns a promise and I can also because I only have this one I can do that I can get rid of these parentheses I have this function which returns a promise and the promise is handled when it is fulfilled the data is console logged when there is an error the error is console.log that's what I have so far right now and here's the thing I want to I want to actually get that word like I want to say data dot word but that's undefined so this is the funny thing about fetch if I go to the documentation for fetch and go under use using fetch yes here's the thing you can start to see that there's something like what I'm showing you here but there's also this like dot JSON so the thing is the thing that's coming back from fetch I have to ask for it to be converted into an object that I can use and that's with the dot JSON function so let's look at how I would do this so here's the thing the dot JSON function also it returns a promise so what I really want to do is this I want to say when the data comes back call dot JSON and then guess what so this is really the response convert that to JSON and then take the JSON and console.log log that which is like this alright let's take a look at this so now you can see how my sequencing is much easier to manage I don't have callback L I actually just have the things that have to happen one line after the other boy this is tough stuff whoops there we go and now you can see I have that word and now okay so let's get a little bit better here because what I really needed to do was call my create P function to make that paragraph so I'm gonna do this so let's take a look at this let's just put that in there now and there we go every time I read so now I'm using promises I'm using fetch and promises okay now I want to next go and try to request a gift associated with that word how am I going to do that now first of all I need to now this is the thing remember with the JavaScript arrow syntax what this really is right here this whole thing right here if I were to rewrite this it's this function JSON create PE write this is just this shorthand but if I want to now ask to fetch the what am i fetching the giffy api if i want to do two if i want to create the paragraph and then fetch the giffy api I no longer can be as short handy I need to put the brackets back because I have two lines of code I need to put those brackets back and that means a parenthesis needs to go here mm-hmm this doesn't look right to me and it's because I have an extra parenthesis here where there should be a semicolon there we go so I have to put the curly brackets back in then I can have two lines of code here right so now first I want to fetch the word Nick API then I want to take the response and convert it into JSON once I have a JSON I want to create the and then fetch from the giffy api so what do I want to do now then the same thing then take that response and convert it into JSON then and then the JSON I'm gonna do this I need to just whoops then with that JSON all I need to do is create the image so I can get that code I had before this is creating an image object and you know I'm not going through how the giffy API works but I in the giffy API I get did I get the JSON data index yeah I get the first gift that's fixed-height small and it's URL so look at this now again this is not so super I mean this is very concise and it's difficult to understand but you can see how nice the sequencing and I'm sure I know I have some errors here but let's at least see how far we get let's see how far we get all right so good news I got the word sketch digest 18 JSON of undefined 18 wait why does that say 18 let me know join this again skip 14 sorry alright so ah so here's the thing promises are chainable right what are the things that return a promise fetch returns a promise which is here risk dot JSON also returns a promise so how come if this returns a promise this worked but this returns a promise this one didn't work well here's the thing you have to explicitly in this chain of promises say return to continue to chain all of the VINs so I actually missed saying return here so if I have to return the promise in order to have the next then sequence properly how come I didn't have to return the response dot JSON promise up here well it's just because I'm making use of the arrow syntax shorthand so I think I want to just remove most of the shorthand here and add back in the curly brackets and say return so and then what am I I need the parentheses here and then also now this is more long-winded than it needs to be but I'm gonna add back in the curly brackets but I just want to emphasize and I've already made another mistake there we go so now let's see can I fit this all in one page here so now look at this now if you if I showed you this at the beginning of this video you would look at me like oh my god you're crazy that makes no sense to me but I'm hoping maybe maybe this is somewhat comfortable for you maybe you have to go back and watch this video again maybe you never want to watch another video in my channel ever but I'm starting with fetch and getting a promise then I get a response back and I'm returning the next promise about converting it to JSON then I returning the then I'm then I'm getting the JSON mmm adding the paragraph and asking to fetch more data once that promise gets resolved I take that result returned into the JSON once that's ready I take that JSON and make an image and then I'm done now here's something that I didn't mention that's so magical about all this each one of these things an error could happen along the way it could break because either one of these URLs could be wrong the data that comes back couldn't be formatted right in such a way that I could get it back to JSON this catch will catch any error anywhere throughout here so if any error happens anywhere it jumps down to here this is much nicer than having to have separate error callbacks for every single thing that I might be doing in a sequence like this so let me now let's hope this works this is time for me to use a drum roll let's see if this works this has been a long video I think there we go it's still working no no no that's the wrong one no no there we go really sound effect challenge so there we go so I'm just gonna now now that we see this full sequence here I'm gonna go back and remove I kind of like using this in once I'm already using the arrow syntax I like to I like to have that shorthand when possible because it does make it easier for me to follow the code so I think and I think I'm gonna keep the curly brackets here because this is kind of a long thing to do so now we can see there might be some other simplifications that I can write to this and there's a lot of extra steps just because of the way that fetch works but this really shows like if I had to do this without promises this code would become really unwieldy and difficult to manage and write so I think I've done at least with this first part what's coming next so I need to show you how to use something called promises all I think so if I want to create like a big array of promises I can wait and have something happen when they're all complete that's thing that's worth showing you another thing is let me make a list of this stuff so can I come over here so I need to show promises all I need to show how to make your own promises how to make your own promises I'm gonna just title the video how to make your problems and maybe people who don't know learn a certain code would just want to know about how to make your own problems how to make your own promises how to promise safai something and then then we're gonna look at I can actually really simplify how this code looks in a really nice way I mean you know you can actually skip all of that entirely if I use and this is an e part of like yes 427 it's a more recent version of JavaScript called a async the async and the await keywords so I'm gonna show how those work and that's gonna even simplify what we did here further now I might be forgetting something that's important in this list and when I come back in the next video I will add to that list as well ok thanks for watching I hope you learned something about promises looking too long and this was helpful to you [Music]
Info
Channel: The Coding Train
Views: 250,954
Rating: 4.9125562 out of 5
Keywords: JavaScript (Programming Language), live, programming, daniel shiffman, creative coding, coding challenge, tutorial, coding, challenges, coding train, the coding train, nature of code, live stream, itp nyu, es6 arrow functions, es6 arrow, map es6, javascript reduce method, es6 tutorial, es6 tutorial for beginners, es6 javascript, promise, promise javascript, promise javascript es6, promise javascript asynchronous, promise javascript example, promise javascript resolve reject
Id: QO4NXhWo_NM
Channel Id: undefined
Length: 24min 53sec (1493 seconds)
Published: Mon May 28 2018
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.