About the Call Stack, Event Loop, Callbacks and Promises in JavaScript

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hello welcome to math math method today I want to talk a little bit about promises I think that promises is one of most important patterns that developed in a java community before we had promises we were doing a synchronous callbacks and we're from callbacks are only the function parents who left to the write down four levers were insane five levels who ten levels we are set color box everywhere we could make sense of it at all promises solve this and promises makes a synchronous code calling a synchronous coding pleasant so today when I look at the call stack we're going to look at the deferred functions and we're going to show how to provide callback hell into promised hell let's get started okay in order to understand why promises so powerful first want to explain a little bit about the offices call stack first and foremost let's have a look at what call stack is submitting this file it's for functions that calls each other and the first function called on-air step 1 so what will happen here is going to call step 1 that's called step to that call step 3 that's called step 4 that then starts at the bugger let's try this script and see what happens okay so now we are in the debugger here and we can see that call stack contains all our steps here's step 1 here step 2 here's step 3 here's step 4 since JavaScript is a single thread language only one of these call stacks can be executed any given time here's an illustration of how the Elvis crypt event loop works it can only handle one stack at any given time so it always needs complete one stack before it can take the next one these tags are triggered from click event handler it can be a requestanimationframe callback or a set timeout callback okay back to our editor I'm going to illustrate how set timeout works we're gonna remove this and write a new function function sync and it looks console.log C and then one function call the third function deferred and it logs deferred so if you call them after each other they should log sync in the third in order try it wink it works sync and then the third if you put deferred inside sync the first you print it first and it is but if you wrap this in a set timeout it will be called after sync the strattice set timeouts the third and let's say a thousand milliseconds try it sync and then deferred that's expected but if you set this to zero will it be called first done no we have the same delay here so why is this this is because set timeout tells the auto script don't do this function now do it later but not earlier than this time and since not now means that it's not this stack it has to be as early as in the next call stack consider this animation here we start to stack per drip and a top of the stack or a set time out to the third so deferred popped out from that stack put an another stack and executed let's now imagine that the third had a value that we wanted to get but we can get the immediately so instead of logging the third it will return a spring turn deferred and since we call this here none on the stack you can't access this value immediately normally we will say like this return deferred but there's no such thing when you do it like this it simply doesn't exist because this is not run here are now in the stack so sync must now take a callback function like this and we need to supply set amount with an anonymous function instead function here and in the anonymous function we will run the third explicitly and we will call the callback method with the divert vessels so Const yes and then callback yes what we now can do in sync is supply the callback as an anonymous function supply the callback as an anonymous function function result and then console dot log resolute just to show that this actually takes time we're going to set the delay for one second so what is expected to happen here is that we call sync first we sending this anonymous function that is this callback and then in sync we call set timeout with an anonymous function that wraps our deferred call and then callback is called address that means that rest comes out here again in a function and then we load it in concert let's check this out boom in one second we got the deferred string here imagine now that we have a multi-step process that needs to be deferred we're going to take in your example here get seller synch copied in domain so this is a program that calculates my disposable income so let's say I have a salary of 33,000 I've subtract the tags and also track the rent then this is a match again you serve a amount for whatever it might be now run this and result in nineteen thousand seven hundred fifty imagine that we get the salary from the bank so we this will send a network request somewhere and get the data back this means that get seller will need to take a call back that we will call when we have the salary and here we simulate a slow Network request with set timeouts I'm out and we say ok now we need to change my keyboard settings automatically perfect set timeout and we create an anonymous error function here and this one calls callback with 33,000 after 1 seconds so it's a very slow Network request and we get an integer back in order to make a disposable income work we need now to supply a call back here and get salary and then subtract X and subtract rent so we can't use the return value anymore we need to put it here and we can say salary and then in the callback we can do think we need but now we can't return from this function because this function now uses a synchronous function so this also needs be synchronous so this is tick a callback the return value can be used anymore and and get disposable income needs to receive a call back to so Lurie let's try this one second and go to salary okay so imagine now that we have different things here they're slow so subtract X we might do that at the tax authorities we might subtract the rent with our housing guy so we're going to implement callbacks on these two to see how that works pull back a copy this set timeout which takes a second and it calls a callback with the incoming seller here times 0.75 the return value goes away same thing for subtract rent it now needs to take a call back and it calls the call back with salary minus 5 tells them and return statement goes away so now these functions don't have a return value either so we need to refactor this cell array to here one last time and salary and finally in subtract whant we can call a callback okay so because all of these has one-second delay let me make this a little bit more clear what is going on so I'm going to call this celery step or a cell everyone then we call with celery one get celery to back call this with salary to you get celery three back and return salary three and here we go to get back income know this folks a little so let's run this I see what's going on one two three ah there it is very reliable so the reason I want to show this is how messy it gets with a call back all the functions that lead into your deep function that is a synchronous needs to have a callback in the function parameters and this is really difficult to refactor after a while what the problem is do is instead of you sending a callback it sends back an object that you can send a callback to and it is much more nicer because you can actually use the return value instead of preemptively send something to the function let's start for factoring this using promises so we remove the input callback and instead we return a promise error return new promise and the call back in a promise you should call it resolved so we're going to do that here to resolve let me put this in here and instead of calling a callback we call resolve let's just show how to use only get salary to begin with let's remove this and see if we can fold up these things that we don't do not going to use now soup soup so now we can say get salary and we get the promise back host promise then on the problem is we can call them then is a method on the problem it's object that puts a callback in the promise chain so here we will get out this salary we can take console dot log seller so this should hopefully log 33,000 in console no did I spell something wrong yeah I'm missing an e here there we go okay since we can Shane functions the over script on return value this thing can go away so we can simplify it to your say get salary dot done and then we get seller here this is usually how we see promises written today we see it our windows the same the same thing happened so now we want to simplify our Shane here and make everything promise viable so we say the same thing in here turn new promise resolved and we update this callback functioning here to solve and we delete the callback from the function parameters the same thing goes to subtract rent return new chrome is resolved update the callback to call resolve instead and remove the callback from the function parameters okay let's refactor get disposable income now I mean get disposable income I'm going to do this in a non-traditional way just to show exactly what's going on so let's start with get salary cost salary for all miss equals get salary and then we Shane salary promise salary for mist of 10 and here we have here we get salary one out and from this we return subtract rent with celery 1 what we get back here now is actually a new promise that is chained to this every time we call then you get the new Shane back so const front promise actually did a little bit of mistake here i need to refactor is this is actually subtract x we want their subtract X and it is the tax tax promise and then finally we can change the tax problem is with subtract rent so we say Const rent wrong miss equals tax promise dot then salary - and this one return subtract rent with salary - then now finally we can return the rent promise here so this should mean that I can run get this possible income then get the disposable income immediately R this is possible well this might look a little suspicious here because it's hard to see really what's going on but all of these things kind of happen in the same time and then we return the rent promise immediately in them this function so all of these basically are chained up events to handle in the promises so nothing here is especially synchro's is the thing that is in the subtract X in get salary in subtraction that is a synchronous but the seller promise here and the textbook machine the rent promise chain or all synchronous events so let's see if this actually works and then we're going to simplify this code okay so wait one second and that should trigger one thing there we got it 19 750 so now I want to show you how much nicer this can be written because we're use promises because right now it doesn't look like an improvement to be honest so first of all since we Shane everything we can set return value already appear and then and now this is going to be magic because of the nature of promises it takes a callback that if it returns a promise it will be honored we can write just this then subtract tax that's it inside only supplying its function all of these can be contained then we'll call subtract X with the salary here which goes interest and return its value in 1 in the same place so then and this is the exact same thing as this whole thing the same thing goes for rent promise so we can say then subtract rent and we can remove this and since we all return Shane up there we can remove these two so if my calculations are correct this will also work exactly as before bang there it is there is one last thing I want to show before we have some fun with a real project imagine we have two functions that return so synchronously after that time and they are not dependent on each other in this case the text is dependent on knowing the salary and the subtraction rent also but imagine we have two salaries that needs when we find we have like for example we might have two-person household with different salaries and want to combine them then we can say hire get salary one and it's going to be 33,000 and we have get salary - which is 45,000 they take one second each but we don't have to excuse to sequentially we can combine this time into one the way to do this with promises is very easy we can add a new function that's called get celery some and in this return a promise a promise not all and in here we call get celery and get sell you one as items of an array get salary one and get salary two and then here we say done salaries can probably use an raise somewhere here and we return the sum of these how do you do that the JavaScript and I guess we can use array reduce return salary stop reduce and how does this work I think is previous current and then we turn rev plus curve and have initialize with zero so now we should get 45 plus 33,000 in get salary some down here replace it yet seller some and we should get something like a little bit more than trouble there we want but total waiting time should only be three seconds if we had more salaries that need a fetching we can very simply just add them here I'm going to simplify this a little bit so I don't have one and this is going to be super supe D but you're gonna be able to supply the seller here and it's going to come back later so obviously this is completely pointless for this just to help example we have a lot of these like say six they should incur a penalty of six seconds if we do indeed them sequentially as a 10,000 20,000 40,000 a detail Sun Rosa but the whole operation shown take four seconds let's lower these timeouts 200 milliseconds and this - I wish you see a little bit more than one second for this and it worked having this for free with promises is a huge benefit okay now thought we could get started with a with our lives project there the too much mustache I can't pronounce the words okay back here and we even eat all this and my product will be I'm going to talk to an API do something with API data and then present the results so I'm going to use the Spotify API so we're going to find this one Spotify API and here we have a good resource a think go directly to endpoint reference we don't need everything else because we are pro so I'm going to start by searching on something a search type artists let's check this out okay this is a great start you can start by writing this in in a program and something that's a little bit new now is that we're going to use the fetch API it is a replace at XML HP request and it's very simple and it's promise based which is perfect for its tutorial so we just say fetch and we supply this URL here then I think it needed a cue here and the string we should be Mike Jackson as Jack Sun CR we URL encode it from the head type album I think it should be fine so this returns a promise that means that we can write down here then we spawn make a little bit more freely here response and console dot log response let's even run this and see what happens Colome okay so we see here that status is good this is where what we're fetched and we have the headers here no we don't do never mind that and the body we can't get yet because the rest ones that you get from fetch needs to be converted to something else because fetch can get images you can get text it can get anything and in this case we want Jason and the fat JP is response object has a built-in method for getting the json data from the response and it returns an object so if we say here return we actually can do it immediately responds to JSON so what we do here is we get two response out here then we run the JSON method on the response object which means that we can Shayne here again and get the data out the JSON method automatically converts it into JavaScript object from a string let's load the date their data and let's try again see okay here we have a nice so big that we can browse so what we do now let's go into the items and the first one is an album hmm okay so here we get albums so let's say we fetch the first nine albums I'm just going to see I'm just going to look at them and make sure it makes sense there okay that looks good no surprises here and then we're going to remember the path where we had albums dot items index dot your eye so let's see if we can loop over this Const your eyes make this an array here with your eyes just check actually we can do a little bit fancier wish a beta dot albums dot items dot for each and we can get out item here and we return I done got your eye I think this should work and then we consult along to your eyes all right here instead No hooray what's in item done it's probably wrapped in something so hmm can't I read now this is each item here well and it's dot your eye what okay let's see what was the error I got again oh this is what is referring to on the fine now cool I can't do anything right today of course we need same map here there we go nice and dandy we have several your eyes here we only want the first five so we're gonna slice this slice you do this not sure about syntax slice no so I guess we need to say where we start here we go now I got five so weary of course wasting a little bit of day there but that's fine okay now we want to use these your eyes to fetch data from a new endpoint so back to the API and what else do they have hmm we have album your eyes now I think so we fetch album data here okay doesn't seem to be any anything surprises here so let's let's create me or your ice so now we're going to use this dry list and create new promises using fetch so I'm going to call this new array tasks cons tasks just constant asks equals your ice dot map and fleet your I we say fetch and what was it / drop let's copy this plus your I so now in these tasks array we have a bunch of promises so lot log tasks let's have a look at them there are five promises all of them failed perfect let's see what we wrong we miss anything important there I'm gonna test your example to make sure I didn't I didn't clumps if I myself they yelled oh I don't need that girl okay that works what's wrong with mine huh it don't last ID so we don't need a Spotify things that's a dumb okay no problem you ride out split hold on and return the third thing third thing okay let's see how this goes okay we have promised us that didn't collapse and all of them were resolved so this this promise globe or promise array we can now put in promised at all so here we say return promise dot all tasks and we create a new link in chain then we can say here we had responses responses we say albums actually and we can look at these albums also looked log albums and let's see what we have now bunch of responses no data please convert into JSON no problem and what is the easiest way to do this do need a new resolver here I can i yeah I guess we do Thomas at all and Adam Scott for what map album and response and response at JSON here so do you have all parentheses there's the map boom wait let me split this into one more row but I'll turn because I can't read it now actually there we go and then here actually once a response this is that and responses then I'll add them out there and see what we get okay now it looks better Ciara's old albums that we got out what do we have here the essentially make the XS good one I bought that at the gas station ones mmm cool cool we have images here great I want this let's use these images for something so back to the code and back to the browser because I've got to see forget to memorize how it looks with object dot images then an array and we have a bunch of height and width I'm gonna do any solution just take the first one because it looks like that is the biggest let's try this and now we need to fetch these images so we say return new Oh promise dot all and we can say here albums dot map gonna route we're going to create fetch responses or fetch request football and here we get out an album and we say fetch and this should then be I think we got the full URL yeah with it so it should be images index 0 dot URL album images index 0 dot URL and here we now should get out responses again we spawned cysts and I actually don't know what the response looks like when I fetch it with an image so let's have a look load responses now I also want to look at Network requests forgets this can be pretty interesting see what we're doing actually so the first thing here here's the search thing then we query more albums album at that oh look at here's why that's wasn't pleasant surprise is my nickname air palm and ID ha I've I don't know what's a but it's an honor Michael Jackson I hope is a good album and which is it it is not too long didn't read never mind that done and then lastly we have the images here the ripped it through very cool very cool and we couldn't see the images okay never mind so I think you need to Google is because I don't know how to convert this to a readable image so I'm going to say here fetch API is phones to image see you have some we here okay URL up create a URL from the blob okay we can use this let's start with us so now we're going to create a bunch of images here instead we say return home a start all um yeah homes at all and we say we sponsors dot map these forms still to respawn stop blah blah and blog just means whatever data it is in it I guess then blobs haha I want to look at their blobs here and I actually don't know what it's supposed to look like hope I don't get scared blah blah blah blah okay and this ah cool we're gonna return all the blobs at object URL return blog the dot map and globe to what was it you created with URL there who then we can Shane if iam then URLs I guess I don't this that part of API is a little bit funky I think URLs okay let's have a look what this looks like okay I guess this is GI IDs from the mmm-hmm okay I guess this is you IDs from the browser cache or something that's pretty cool I guess nice so now let's just show these images on the one account my Sarah on the on the Dom oh let's do another Shane here a turn turn your else dot map URL equals M homes image equals new image and then image of SRC equals URL and return image hmm we can do another thing here to make this a little bit more extravagant we do like this pattern Rome is too tall and we map over all the URLs there but we create a new promise here now here return new promise we solve and it doesn't return image but on image download image to add event Easterner what is it load then we resolved and and actually I want to be a little bit more expletive ear and say like this resolved and actually send in a mature okay I just need to check there that I did everything right so chrome is a tall and URL stop map I think this should be okay and then we should get out a bunch of images here but then images console.log images here they are now we can't put this in the dome let's erase this inspectable blah bear so we say images dot for each image and document dot for date of appendchild image boom hello darling well that's pretty cool and that everybody is how we make a complex multi-step promise chain and as you can see everything looks very nice okay lastly I want to show you how the equivalent code for this program would look in using callbacks so we have this file here somewhere will you put it there this yeah that's how we will look if we use this the callbacks to send if I have any questions
Info
Channel: Meth Meth Method
Views: 31,589
Rating: 4.8539767 out of 5
Keywords: JavaScript, Web, Programming, Promise API, Fetch API, Spotify API
Id: RRgAdi3gX-s
Channel Id: undefined
Length: 41min 3sec (2463 seconds)
Published: Thu Sep 01 2016
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.