 Namaskara J. S. Fu. Thank you for being here for such a long time. I'm going to end the day with a story. Story of Ved, my son, who wanted to learn some serious JavaScript. Then I suggested him not to read so light versions of JavaScript, but to read something serious. JavaScript for babies. He did read that and his first assignment was to read a file as simple as that. He said, well, that's easy. I'll just do a read file sync. Give me the file name. I'll read it. Okay. But it blocks. He said, okay, he learned some more. And he came to the callback version. Instead of the read file sync, he started using read file and then gave a callback to it with the file name. After the file is read, there's a callback. If there's an error, you return callback with the error. Or just you return the callback with no error and result. This is the normal drama we all of us have done so far. Okay. That's not bad. Now you want to process a file, the same file you have read. Now you have to do some process on it. How do you do it? He said, okay, that's easy again. I think he started with a simple function called process and for which our data and the callback is passed and the remaining pattern of reading a file and checking for error and handling the callbacks and then written in the callbacks. And again, a callback in the process continued. You rang. I heard you like callbacks. So you can put your callbacks in your callbacks and call you back when your callbacks are done. Right? This has been the common slide most of us use from Mozilla where it explains about the pyramid of hell. This is an example where you want to cook some rice, right? So you pour some water, bring it to boiling temperature, lower the heat, add some rice, set time out and how many callbacks we already have to eat our rice, right? Promises. When you know, then you know, right? Promises are some objects that can that resolve that gives you some result and it's kind of promising you that I'll give you some result on a period of time, right? It can go through different states. It can be fulfilled or rejected. If it's fulfilled, then you'll chain it with them. If it's rejected, it will go to the catch. The fun part is with then also you can handle both rejection and fulfillment and finally it is settled and you have some operations and the idea of promises is you return a promise and then you chain it. So again, it's like you could change your promises with thens and catches, right? After you catch, also you can do it then. Here's a simple example where you do a new promise and you pass in a function with resolve and reject to it. If everything goes well, you resolve it. If there is some problem, you reject it with what the problem was. Then you can do a promise dot then and the first callback that comes in would be the successful if it's resolved or else it will be rejected. Here's a simple node module I've written called li-fs. But today, if you're on the latest versions of node, you can use the promissified version of fs, fs slash promise, which comes as an util within node. But with li dot fs, what basically it does is it promissifies all your fs methods. So in this example, if you want to know the stats of your temp directory, you can just do fs dot slash fs dot stats on temp and you get a promise. You can console log it or error it out if there is an error. But there's a problem again with promises. If you're not careful, you would end up with something like this. Well, there are mitigations similar to how you can escape callback else. You would name your functions, name functions, keep your promises separate. All those things are there, but it's not guaranteed that everyone would practice that. You would have seen many of the code bases having this kind of a thing. Here's one more real-world example where you connect to the database and get the user information and get the user settings and then finally enable access. So it almost looks like the callback hell, but with more of a chaining of them. How many of you know this guy? Awesome. Yeah, so that's TJ. TJ wrote a blog post a few years back. He said streams are broken. Callbacks are not great to work with. Callbacks are vague. Tooling is not so great in the community. It's not so great. And community conventions, it's kind of sort of up there. For a very long time, I thought TJ was a company. The amount of code he was churning. But luckily I happened to maintain one of his repose it extras. Then I believe that, okay, TJ as a person exists. But I was seeing this pattern. Even though he quit note, he was pretty active on this project called CovaJS, but and why TJ also felt and I think he saw the future. Welcome to Jurassic Park. I think, I wait. I think is a keyword when used next to a function. It indicates that whatever you return in a function would be a promise. It could be as as simple as return one. So if you have a function and you say return one, it would return a promise that would resolve to one. And I think functions of the function are only those functions where you can use this await operator, right? And what is await operator? A wait is an operator that suspense the execution in the scope. So what I mean by that is suppose you have an async function and you are waiting for a promise to resolve. And it kind of suspends the execution, the order of which it's as you assume, like it's pausing the flow only within that async block, right? And then it will wait until the promises either resolved or rejected. If the promise is rejected, it will throw. So in 2016, I said a year 17 or years 2017 will be look the code where we write would look like sync but run like a sync. And in 2015 at three in the morning, I said, I said like JavaScript await is no fun till it gets an easier way to capture rejected promises. In 2014, I kind of did a talk on async await when it was in a proposal state and people said like, dude, it doesn't make sense. But today, this is how we can define an async function. The emoji is just for the fun of it. If you want to define such kind of function, you have a plain object and put the emoji in the string, then you can still define. And you can see async function and see await is normal like the normal function. And you can use an arrow function or you can use a generator. Here's an example from the code base. I think I can point to this. All right, that's fine. This example is from the spec. What it is basically doing is it takes an element and set of animations, applies the animation on that element and finally returns the final value after applying the animation on the left is the promise way of doing it. We basically have a promise dot resolve. You could also read you can rewrite this with produce, but you basically have a promise dot resolve as your initial promise. And then for each of the animations, you use you do it then apply the animation, save the result and finally return it. If there is an error, you'll catch it, of course. If you were to rewrite the same thing with async await, it would look like this, right? You have an async function. You have a try catch block. And for each of the animations, you just await for the animation to complete and you have the return value in this. It looks so intuitive, right? You can just if you can just take it as an example and read what's happening on the left and read what's happening on the right. Or for you, it is the left and right. And then then it's so intuitive to read. It looks as if you're writing an asynchronous programming, but because there is await, it is asynchronous in nature. Demo time. So I had written this, you know, kind of a XKCD comic fetch. How many of you follow XKCD? Okay. Awesome. So what it does is basically get fetches me a random XKCD cartoon. You're not able to see that. All right. Hey, this, this screen is not coming up there probably because I'm on full screen. Okay. Or it's tough to see the big screen and type and enable the mirroring, but this is not working. Just a second. Sorry for that. All right. So basically this endpoint gives me a random XKCD cartoon. It gives me the URL and then gives me the title. Right now. Let us go through a journey of fetching this URL from the console and see how the journey goes through. We start with XHR. Oh, it's big now. We do a new XML HTTP request. The name is XML HTTP request. No more we are doing XML calls or it's an HTTP. It's more like Gulab Jamun. Neither it's Gulab nor Jamun. Right. But, but we are lives as JS developers for this. Like this is like the gift from Microsoft where the people enabled the XML HTTP request. And we do XHR that dot open, which takes a method. In this case, it is get and that's not the URL. This is the URL to which we're talking. And then I'm not sure how many of you are aware or have used this last parameter. The last parameter makes this a synchronous call a synchronous network call. Right. That's where Chrome spits directly on your face saying that. Hey, don't do this. And if you were tried, if you try to set the response type on this, you can't do that because it is synchronous. Right. Now we kind of say on load and we will console log image. Yes. Console log image XHR dot response dot data dot. What is the thing we were getting response dot URL. Right. And then we send. All right. We got the response. It said title and URL. Right. Console log image. We got was this. Yeah. This is how it should have rendered right now. It's it's totally from the server. Nothing is marked. It's not my fault. And we do a new XML HTTP request again. And this time let's let's kind of make it a synchronous quickly. Right. We again open up with get but we'll not pass this false here. And then on load ended we'll take this and let's quickly log what are we getting on as response. Right. Response dot data dot URL. Okay. And then we send. So it's not data dot URLs for sure. Right. We open again. All right. That's the shortcut way to do it. And we have done an open. We'll do a send. So it's URL. It should it should have just been XHR response dot URL. Right. It's a string. Okay. Very attentive audience at 5. PM. All right. We open again. And we send. All right. That was perfect. So we get the point right. We'll we'll go into the next one and we'll pass it out there. So that so we started with XHR. We did a synchronous call. Then we did an asynchronous call. We saw the network request call happening. Now is the time for jQuery. Right. With jQuery. What do we do? We do a get json. Right. And then our URL. I better define this as an API somewhere. Right. I will call this API and passes here and we do dollar dot get json. Okay. And then we pass the API and then we pass the we get the callback. Right. Which has the data in this case will the data be passed. Or not. Is it passed now we do image and data dot URL. Okay. So we have the image in the console. All right. Now this was jQuery. So we did the synchronous asynchronous jQuery and finally what's up next. Yes. We will do FH API. And it returns a promise. So we would do it then and say we have a D and this kind of gives you json. And then you do it then again. Call this response and console dot image response dot what would it be here URL. Right. And then if we would probably need a catch if there is an error. Right. All right. Let's see. Okay. There we go. That's neat. So how do we take this further? Now let's try a sink of it off this right now we will remove this. We will say await fetch one gotcha here. You can't you can't really use await in the top level. There is a proposal for top level of it. What do you mean by top level is basically you need to wrap this line in an async function as mentioned earlier because this depth console. If you use a top level of it it kind of gets wrapped with an async function. So you can do do an await on the dev console without wrapping it in an async function. Right. So we do an await. We get a response. Right. We would have a json on it. Isn't it? We will do an await of that. We get the data. And we console image. This right dot URL making the request. So we wrap this entire thing. This is fine. Right. Yeah. No, as in where the URL is coming. That's fine. So we wrap this entire thing. We get this. Okay. There you go. It's a really bad way to do it as we noticed having await await await in a line again is just for the demo purpose to show what we are waiting for. And thanks for being an enthusiastic audience and highlighting all the scripted mistakes. Right. Awesome. So we we saw we kind of read we kind of saw the journey of starting with the synchronous to asynchronous to jQuery kind of a thing to an await today. Right. Let's get back. Can I have more? We kind of saw how we do this. It's kind of clear. Okay. So here's a quick quiz question on what would left print or log and what would write log by intuition. The left looks like it would log ABC. Right. Right. Yes. No. Yes. But no, it will not. End up logging C B A. But why? What's the difference between these two? The key difference is we are waiting. There's a written await. The other one would print ABC. Right. So it's a key point to remember that when whenever you're waiting, if you're if you're returning something out of a weight, which is kind of an obsolete, this just to show that how await kind of makes a difference. So if you're returning something in the try, which has which has a promise and your functions are sync, make sure that you're awaiting for it. That's when it waits for that promise to get resolved in this case. It doesn't really. Right. So that's where you know how the how the pause kind of mechanism is working. And suppose you have two async functions. Right. You kind of await for it rather. You could use promise dot all and say await or await of promise dot all and give two async functions, whatever it responds, returns would be R1 and R2. So there was also a proposal for await all which kind of got rejected. And at the very beginning when the proposal was there, there was this proposal called await star, which was doing this, but even that's not there. And in the in the previous talk also, we saw this async dot waterfall being used a lot. Right. Now if you were to rewrite async dot waterfall async dot series with async await, how do you do that? On the left, you have waterfall where you have await await async function one. The results of that is in R1 and then you have await async function two result of that R1 is passed to this. So you'll get the result of R2. So it's behaving more like a waterfall on the right. You have the series, which is pretty simple. You can return an array of awaits. And if you have an async iterator, you can use. You can you can iterate it with an await. This is because you can't do an await of for each, right? It is not, it is not like asynchronous where you could use await and wait for things to get resolved or whatever processes you're doing. That's where you have to use this loop called for await of. And if you have an iterable in this example, it's just a simple iterator where it kind of returns and results to promises and you can await for each of them and log it out. So the other example is where instead of you using promise dot all always, you can have an all higher order function where you pass in the parameters and do promise dot all there. If you want individual, you can just pass like P1P to all your promises or you can just read it out and send all the request and get it back to an array. And also you can use await on any thenable function as in in this case, you're seeing it's just an object which has then the blabber loop is like resolve and reject. You can just await on that and it just console logs 42. So it need not be a promise. It can be any thenable function. So if you have a class which has thenable in it, you can easily wrap it in an async function and await for it. And if you were if you're using express and if you want a middleware which has async of it, you have to be you have to do a bit of a circus where you have to wrap your middlewares within with a promise which kind of resolves that function. So basically pass of pass your middleware to that. It's kind of it kind of wraps it with a promise and send it over. Rather, there is this project that I was talking about when TJ was interested on koba.js which basically started with generators and now it has async of it. As you can see the pointer moves every time there is a next await next. It goes to the next chain middleware automatically. So you need not wrap your middlewares. You can just use await. It's a very lightweight module. You could you could try using it. And the pain part if you have observed is you have to wrap all of your awaits if it is throwing with a try catch. Right? Or you are there is or you could say promise dot something and then do it dot catch again. But isn't it painful to have a try catch block everywhere where your await might throw. So here is a wonderful module called await to JS. You just require it to as to and say await to of promise dot resolve which kind of gives you error and result. Arrays right? So it's pretty straightforward. You can do as many awaits you want without putting it in a try catch block. And there is the fantastic module called proximize. So instead of you writing food or then then then chaining all the dense or instead of having await await awaits, you could proximize your food and then say bar bar skews and you will get the value directly. So it it is like a simple chain. It's almost like you're accessing your object properties. Right? So proximize is one such wonderful tool. And if you want to know more such modules, you can subscribe to my node module of the week. So another final gotcha, a couple of minutes of gotchas like. So you might be wondering if I want to use a sink away today, most of you would probably run it through Babel or something. Right? What happens when it transpiles? You have a while one. Right? It is using regenerators and there's a while one running because the browser has not implemented it has no other go, but rather to implement a state machine in itself and the loop keeps running. So to mitigate this, there is this wonderful plugin called it. It's experimental. I think the PR is approved, but not at merged. It says like, but you can still use it. It's Babel plugin async to promise. If you see here on the left, you have your async function on the left on the right is the transpiled data. Right? So it looks as good as having promises. Unlike compared to the previous one, you had a while one with regenerators and things. The other thing the VA team is working on is when, when there's an error, they've made it better today as of today on node soon to know where exactly the error happened. Previously, if there was an error that was thrown, it would it would just say d8 1 colon 44 and you have to figure out where the error was thrown. But now it's improved and it says like async promise all and that's where exactly the error got thrown. Right? And Benedict posted this last night. It's, it's the benchmarks for, you know, async await and parallel promises. So you can, you can see it for yourself on version 8.72. That's how fast it is. If you're not into real micro level optimization, this is perfectly good to use. And here is the last fun thing that you can do if you are, if you're on VS code, you could enable this by enabling the, for TypeScript and for JavaScript. You could convert a block of code which uses promise to async await. You saw that? Yeah. So you can just highlight the block, refactor it, all your promises, one shot into async await. You could probably get bonus points using this plugin and say like, hey, I wrote, rewrote the entire project with async await, like kudos to me. And support on browsers. These are the supports and browser. And if you're on node, you're like really good. If you're on seven and above eight, you're really good. If you're on 12, you're like a hundred percent, like all the async await features are there. That's it. You can tweet me on new month and catch me on async await.com. Hope you liked it. Thank you guys.