Callbacks vs Promises vs RxJs Observables vs async/ await

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments

I feel like, for explanations of basic implementations like this, it should be demonstrated with traditional function calls rather than arrow functions. More verbose, but makes it much clearer to newbies what is going on. That said, still a good explanation video.

👍︎︎ 16 👤︎︎ u/Rainbowlemon 📅︎︎ Aug 07 2017 🗫︎ replies

That's a great video. Max seems to understand how to explain the guts of what is actually happening in the code and not just a list of steps needed to get something done. As a relative JavaScript newbie, and a quick dive into what arrow functions are, this all made perfect sense.

I'm just going through my own callback hell now, trying to get a payment gateway library to act slightly more synchronously in the form submit event, and this gives me a few clues as to how I'm going to solve this (in the form submit, a series of things have to happen before the form finally submits, in any order, but ALL those things must complete, and any of them can flag up an error and ask for the form to not do the final submit). If anyone knows how to solve this without all these latest ES6 (?) features, I would love to know. From what I understand, it is essentially the same problem the code in the video solves - turns a series of asynchronous actions into a synchronous series of actions.

👍︎︎ 2 👤︎︎ u/judgej2 📅︎︎ Aug 08 2017 🗫︎ replies

Great explanation

👍︎︎ 1 👤︎︎ u/Chaimkeh1 📅︎︎ Aug 07 2017 🗫︎ replies

That was a pretty great explanation. I started learning to program a few years ago and managed to skip right over callbacks and went straight to promises. I've had to learn them since when I look at code bases I did it write. Good video!

👍︎︎ 1 👤︎︎ u/redhedjim 📅︎︎ Aug 07 2017 🗫︎ replies
Captions
welcome to this video great to have you on board my name is Maximilian and in this video I want to dive into a super important topic in JavaScript development handling asynchronous operations with callbacks promises rxjs or async await when should we use which tool and how do they actually differ we'll take a closer look at these questions in this video so handling asynchronous operations is a super important task in JavaScript you're probably going to write or treat any application which doesn't use some asynchronous operation now JavaScript offers you different ways of handling asynchronous operations because by default JavaScript of course is synchronous executes one line of code after the other and therefore you need certain approaches or tools to handle these asynchronous cases I actually did a write an article about that too so if you're more like a reading guy or you want to read after watching this video check out this article where I will dive into the main or the major approaches offered by JavaScript and outline how they work and how they differ and when you might want to choose which of course I'm also going to take a look at this question in this article so let's do this right now for that I created four examples you can find links in the video description and I want to start with callbacks the whole list or simplest way of handling asynchronous code in JavaScript now here on the left you see my JavaScript code on the right you see a button let's click the button first if you wanted s click 'add its first checking authentication fetching a user and then displaying the user the user named max my name okay so what's happening here well in the code up first of all get access to the button and then to the div where I want to render that username nothing asynchronous thus far then I have three functions here I'm using arrow functions the es6 feature but in the end it's just functions the first one is just a helper function which will render the text 1 the user name basically could use it for any text once I got it so here I'm just accessing text content of the day if I fetched and output some text then check off is just a faking asynchronous function where I use a timeout over Q seconds q then do something to which I'll come back and I also call set text to display checking off here instead of the username once I am checking the off now of course in a real application you would probably reach out to a server here for example to verify if some token is valid if user is logged in and here I'm just faking that we have to wait for the actual response whoever it is true or false I'm doing this what set at the time out as mentioned the same for fetch user here I'm always updating the text and then I use a timeout to fake the fetching of a user now you probably already see this CB failure which I call inside the timeout so once the timer finished and that is the argument these arrow functions receive here so CV is just the argument passed to the function that leads us to the question what is the argument and who's calling these functions the argument obviously is a function itself because we execute it like a function passing an argument to the function then this case we're executing CB and pass through here we execute CB and pass a JavaScript object and the one calling CB is inside here the event listener on the button here I call check off then I pass a function that's just another arrow function here to check off that's super important I'm passing an anonymous function here Q check off and remember check off did require a function C be called here you can of course rename the argument here so I'm passing a function to check off which check off will execute once the timer completed and it will then pass true Q that function is got as an argument so basically keep that function of the argument of that anonymous function will be true in the end because I pass through to the function pass to check off that this anonymous function so this anonymous function gets called whenever this timer and check off is done and then we pass true as an argument to that function so off will be true and the next time I do check that and this is already asynchronous here this code inside this anonymous function will only run once the timer completed because what we do here is we tell JavaScript hey please don't stop X fusion it wouldn't do that anyways but be aware that whenever the timer is done you should execute this function your dis anonymous function which then in turn executes call back true that is what we tell JavaScript be aware that you have to do this in the future once the timer is done so this code here only runs once it is done once the timer completed then we checked off the value the timer gave us and then we execute another function fetch user so that's this function here that's user and it works in the same way we passed an anonymous function to fetch user this error function here where we expect to get a user then and this anonymous function is now executed inside the timer of fetch user after two seconds we execute what fetch user received our anonymous function we execute it and pass an object to that function so a user here will be that JavaScript object well and then we simply call set text in there so check off is executed and the anonymous function for check off will run after two seconds so after this timer of check off and then inside of that code which runs after two seconds we reach out to another function which uses a timer so that after a total of 4 seconds we will run this code two seconds from check off in two seconds from inside here from that user timer and this is what happens here we click fetch user checking off for two seconds fetching the user for two seconds and then seeing the user these are callbacks and on the first look there's nothing wrong with that right we use callbacks looks like a good solution to that we tell JavaScript to do something at a later point of time so that it can continue executing the rest of the code and then just execute dev coded remembered once it needs to be executed the issue is something we can already see here we're nesting all these callbacks imagine we would not output the text in that fetch user but then do something else call some sir that function which transforms the user then we would have transformed user this function doesn't exist here but we could have that and there we would pass not recall that function where we get the transformed user back which you can then handle in there so handle transformed user and you can already see where this is leading to you we got a lot of nesting going on and this is actually called callback hell because you add more and more callbacks and it gets super hard to mention to understand error handling becomes a pain because if you handle an error inside a callback you probably want to call another callback and that's no fun hence Java Script gave us a solution to that with es6 or already earlier if you used some third-party libraries promises the general setup here is the same I still fetch get access to the button and to the depth and as you can see if I click this it works the same as before checking all fetching user outputting the username but the code inside check off and fetch user changed here I'm not calling some callback anymore you can see these functions don't receive an argument anymore instead I'm returning a new promise and promises are a construct a class introduced by es6 promises as their name suggests our classes which promise a certain value in the future so they're also a tool for handling asynchronous code in this case here the promise or always a promise if you create one on your own and as a side note oftentimes you don't create promises on your own but you use some third-party library like axioms for making HTTP requests which will automatically give you a promise but here we're creating it on our own we created on your own recalling new promise and to the promise constructor I passed an anonymous function which gets two arguments result and reject these are actual functions you can execute inside that anonymous function here and here and then is again creating a counter a timer inside my promise anonymous function and after the two seconds I call the result function here which will basically inform JavaScript this promise is done we got a value and this is something you need to do in the promise man because you do promise a value you could also call reject to throw an error but here I'm just using result and then we result true at the same for the user here I resolve my JavaScript object now first look you might say well that doesn't look that much easier than for cold X now but again keep in mind oftentimes you're not the one creating these promises oftentimes you will use some library which already gives you promises the interesting part comes if we have a look at how we can use promises down here this is much cleaner code we listen to the click and then inside this click handler we call check off and then we don't pass any function to check off which gets nested but we simply call then change to the check off call now then takes an anonymous function where we handle this value we get back from the promise so true in the case of check off that gets stored here that gets automatically passed as an argument and then I simply return a new function call return fetch user calling that second function which all returns a promise keep that in mind now here we're returning this and in the past we would then kind of like ever use a call back in there or with promises you could think you've now called then their cue but the cool thing is if you return a promise inside of then block you can simply chain another event block after the first one so you never have this deep nesting of callbacks or anything like that you simply have then after then after then until you're done like here that's the last then block we then get a user which we output so if you got deeper layers of nesting promises are great because you never get the same behavior there you just have then after then after then and it's also easier to handle errors you could read more about that in the article I mentioned at the beginning of the video so that promises already a great tool do we need more well there is another construct named rxjs which gives us observables now our XJS observables are not a native javascript features like promises are but they are made available through a third-party library rxjs is the name of the library same code as before here when it comes to getting access to the Dom but then check off and fetch user do something else something different they return and observable basically it looks at bit similar to the promise we create something here and then we pass a function to what we created and in there we call set timeout and object to seconds we call in this case the observer and the next function but that's kind of like resolve for the promise we basically emit a new value a core distinction between promises observables is that promises handle one value you send the HTTP request you get a response you resolve your promise you're done for observable that's different you can handle streams of data there you can wrap and observable around a click listener you listen to every new click and emit a new value on every new click that's not possible like this with promises here again we're just setting up our simple observables and then down there you see this wrapping around an event in the past we used add event listener on the button here I'm using an observable method to create a new observable from an event an event on the button the click event and then here we're using something the rxjs library offers so called operators and there are loads of operators made available I actually do have rxjs series on this channel in case you want to dive deeper these operators are great though because you simply chain them after each other so likely then calls for a promise here in this case switch map basically handles the first asynchronous value which comes from this click event so we get to click event and let me call check off and that's just a short es6 arrow function keep in mind that this in the end returns check off that's important to know so we return whatever check off gives us and check off just gives us an average servable we call another switch map which will just take the last observable so the one return if I check off it Maps it into a new one in this case the one we get from fetch user so we use the value from check off and return a new observable and in the end that that is something you have to do in every observable you have to subscribe once your chain ends so what you want to do after you went through all your observables in this case we subscribe we know that we will get a user in the end that's just what scheduled gets returned back that user and we can output it here and hence if we click this we get the same behavior as before but now using rxjs and rxjs can be a little bit more complicated to learn although due to the many operators that offers but being able to handle streams of data again not that easy with promises and having all these operators which can be complicated I'll give you that but which also offer use so much possibilities and opportunities to work with your data streams these are two arguments really in strong favor of rxjs and personally I can only recommend trying out rxjs observables and working with them they can really enhance your project quite a lot on the other hand it's of course not the perfect solution for every project if you guys very simple asynchronous operations you don't need to handle data streams and you don't need all these operators it doesn't add that much value to your app to bring in the rxjs library which of course will also increase your final bundle size that's something you have to keep in mind it's not a native JavaScript feature so it will add to your bundle size but if you are working with data streams or if you do will see that these operators add some benefits definitely check out observables so observables are awesome and promises are good alternative what else do we have then I think a wait that's a new feature coming with JavaScript es8 still you can already use it with some transpilers like babel for example and adding some polyfills probably here we get the same starting set up and then we return promises just like in the promises example the code up here for check off and fetch user is exactly identical because async await just uses promises behind the scenes that's super port to keep in mind async await uses promises it's not a yet another alternative it uses promises it gives you a different way of handling these promises once they resolve or reject though let's scroll down here we have our event listener and if you check this code it looks very synchronous doesn't it we create a constant we initialize a user variable with the if check where we set the user variable and then we set text this looks like synchronous code one command running after the other there is no nesting with callbacks no then calls and no subscribe calls from rxjs there are cue important keywords though async and a weight async has to go in front of your function definition so here we're defining and passing an asynchronous function excuse me an anonymous function just a normal anonymous arrow function and we turn it into an asynchronous function by adding the async keyword in front of it now to JavaScript this will signal that everything inside that function may use the await keyword to pause the JavaScript execution you could say that is what await does here we assign a constant and we tell JavaScript the value of the constant should be what to check off resolves to what the promised return fight check off resolves to keep in mind I said it two seconds ago async/await uses promises and only works with promises check all pro turns a promise and we can then wait for this promise to resolve and JavaScript will basically wait or behind the scenes use then again wait for check off to to resolve and then store it here and only then it will move on and execute the next code line that is why you can only use it in especially marked functions because the default behavior of JavaScript is a different one each line gets executed after the first one and it doesn't wait for some async operation to finish now here in such async functions it kind of does and we signal it for to wait with a wait the same here for fetch user which held JavaScript don't execute this line set text before this operation here is done and we stores the resolved user in the user variable here that is why if I click this button we see the same behavior as before but now without calling then or using coal bags or subscribe a thing away therefore it's a great tool to write easy-to-understand code which looks like synchronous code and therefore definitely a tool you should keep in mind and you should use when working with promises and when working with chains of promises where you have a lot of then blocks after each other maybe because you can write very clean code with async await just be aware it's always the combination of async and a weight you can only wait in async functions now again check out this article I referenced at the start of the video if you want to learn more I hope this video gave you a good overview over these four tools for handling asynchronous operations in the video description you can find more links with more resources to dive into these different tools and you learn more about that if you want to do that I hope you enjoyed the video see you in future videos hopefully bye
Info
Channel: Academind
Views: 129,952
Rating: 4.9289341 out of 5
Keywords: javascript, callbacks, promises, rxjs, observable, observables, async await
Id: jgWnccjXR4I
Channel Id: undefined
Length: 20min 26sec (1226 seconds)
Published: Fri Jul 28 2017
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.