Javascript Promises and async/await Tutorial

Hussein Nasser · Beginner ·🛠️ AI Tools & Apps ·7y ago

Key Takeaways

This video tutorial by Hussein Nasser covers JavaScript Promises and async/await, providing a comprehensive introduction to asynchronous programming in JavaScript, including the use of promises, async/await, and error handling.

Full Transcript

promises are JavaScript constructs which allows us to perform asynchronous calls without blocking the UX or the UI or if a client that is consuming this asynchronous function they are designed especially for operations that include a lot of waiting like making a rest call or making a network call or way like a timer having a timer running in the background so this is like what what promises are designed for in this video we will learn about promises and how we can use them right and we can learn about how we historically have done this before promises came into the picture and we're gonna learn what is after promises this is coming up what's up y'all this is who say nothing from my geometry where we discuss software engineering by example I'm feeling you here welcome we discuss all kind of software engineering in this channel so if you're new you're consider subscribing let's just jump into the video guys so in order to discuss promises we really need to know what came before it right we can just look hey this is a new thing go learn it I don't like to do that I like to come back and see why we are inventing and your technology it's always there is always a reason for everything in life okay and this is one of it right and I just learned this new sweet thing here just like in Google Drive this is the what is it calls a slideshow whatever this is the PowerPoint version of Google I don't know what it's called right what this is so sweet all right so this is this is the callback I'm gonna overuse this guy so bear with me I love this stuff so callback function is what came before promises right so when we deal with asynchronous stuff right when we make an asynchronous call we wanted to know that hey let me know if your function succeeds right so what do we used to do is like you would give it a callback function say say hey this is on success call this on air or call this and it used to work beautifully but coding was miserable guys if you if you know what I'm saying if you wrote asynchronous code there it is I'll play because you got your end up in two nested functions and two nested functions tuned into the function and you cannot read this thing so JavaScript the community beyond just came up with the promises which made it a little bit better but there's something better than promises right that it even made it better and better okay but we'll come to that so that that was Colbeck fun so that's the first thing we're gonna discuss callback functions right so promises that's the and we're gonna write right back callback function from scratch right show you how it's done right promises we're gonna replace it with that promise using dot then don't catch right and gonna talk about that we got to talk about does finally which is a new stuff and promises right and finally we're going to talk about async await if you win once you have a promise based function a function that returns a promise you can start using async away which is pretty cool I think this is where everyone's going right I mean I mean it's really you're gonna find out after at the end of video I'm gonna ask you a question and it's all I think it's a preference some people like to use promises like dot Nando's catch some people like to have it async await it's up to you as a developer to choose right that's it let's just jump into the code guys okay guys so in order to start working with this video you need a text editor my favorites visual city code download that it's free it's the best right and you will get it almost so need a web server okay like I'm gonna use node.js with HTTP - server gonna refers the videos that let's just jump into the video and create a new project right so I'm gonna go ahead and create a new project file open a new project is really just nothing but a folder guys alright so I'm gonna create a new folder I'm gonna call it promise demo right and then I am going to open that folder and voila I have a brand new folder because JavaScript code lives in D after you know obviously you can do the same thing exactly with no J's right but it's easier to run in the browser guys write HTML right let's spin up a just boilerplate html5 and we're ready to start coding guys all right so here's what I want to do guys I'm gonna add a script tag here that and I'm gonna write a function with a callback function right that's how we used to do that and this function is called due day right right it does something and what it does is it imagine it when you call it sometimes it fails sometimes Sexy's long obviously this is an ad this is like made up right this is just like it's not it's not really a true scenario but I want to simulate some sort of a network call that sometimes fail sometimes succeeds so what we're gonna do is what I'm gonna do is literally generate a random number right I don't know n and then multiplied by thousand because it's fraction and then literally just do a percent right okay so just a random number cool this is better right so just random number and if this number is ah if it's even this is a success and if it's odd it's a failure I know obviously it's completely made up right contrived that's the word I'm looking for oh my god okay okay so what we used to do thing is you would write this function and you would pass in a callback function if it's X is called this function if it failed call this function right on sex is on error so this is exactly what I'm gonna do but I'm not gonna immediately fail I'm gonna just simulate like a call right so I'm gonna do a set timeout and add the callback function here is like whenever you're done after like a second Kol success right and then why not pass in the number that you succeeded on right and this is like a thousand okay and the same thing exactly when this is file on air or okay and then you pass this thing right and that that's it right that's that's how we write the that this is how we classically do thing right you we used to do that in the mid 2000s and even early 2000 right and so because you can Java some you can pass in a function just like mmm a lot a variable you would able to do that so let's use that let's see how how we actually use that guys remember so here I'm gonna call due date okay and it needs a function when sex is what do you want me to do right so this function because look at that it actually takes a number so I am gonna take a number here let's called n this is an auto function guys so this is like a simple error function I'm gonna literally pass it a function that says I say structured right and then and right the second argument is a failed function right so I say console dot you can do those lot but I'm gonna do error because it's just like if the browser Labor's a different click right there are then you can do that okay so this is one way of doing things guys but we can just use this nice sticks that to replace this this is exactly equal to this right so just showing you different things you can do here alright and we need to be fancy right we need to be fancy sometimes okay so do that and that's that's we're gonna do right so let's go ahead and spin up my server here I'm gonna create a new terminal and then literally I'm gonna type HTTP to share that and then click that and and I have made a video about that like how do you spin up okay no js' static file server you can if you're using windows literally copy this index.html and do i'm it pop ww root if you have iis and that just will immediately work for you okay so my server is running on localhost 8080 let's just spin that up guys spin it up localhost 8080 right let's go ahead and open the developer okay and you can see that we got a sex search we got an error what parce praise praise the Lord praise the Lord we don't know how to spill guys praise the Lord parce and not praise oh my god praise the Lord and there is what the heck parts end you think me parse ant is not what parse into Jack oh I'm sorry it's parse with okay so it's not lowercase alright sorry guys about that right so refresh right and there you go that's what I want to see that's we got an odd number so header so if i refresh again because success look this is what I'm talking about right sometimes I'll get a sexy sometimes gonna fit based on the number so that's example of a callback function okay this is how we used to do things back in the days right so what's wrong with this guy's looks looks cool right but here's what a good really problematic let's say if you call doodad right and it's sexy do you want to do something else right so you're not usually just printing things like this right usually what do you do is like hey when will you call this function and it succeeds I want you to really call it again right and do something else right and especially when you're calling wrists and points and you're waiting for a result you get that result and you want to do something with the results so you don't end up in this infinite kind of ugly code right and you just it's already just with two layers is already hard to read right so that's that's the ugliness that we want to get away from okay that's where it gets really ugly so promises promises how can I use promises guys so I'm gonna write my do that 2.0 function but I'm gonna promise a promise from a fuss promised if I do that - is gonna be a promise based function as more as much easier to say okay so do that - well this is how we do it how are you promised pacifier you immediately return a new promise okay you get back resolved you call this thing you get back a promise and promise is this chainable class chainable object that tells you hey dots then dub bent up meant that then that catch right so that's that's essentially what a promise is right so what do you do is like you return this but a promise right a promise is expecting you to do something because it's promising you to do something you gotta give it something in return man so what do you do is you give it a function and this function right that's what you give it you give it a function this function takes two parameters resolve reject right which are in in their in their self they are functions right which is equivalent to your own success and on and on fail if you think about all right so what happens here is when you call do that - it will immediately return new promise and you will immediately execute this function for you and whenever it's ready it's gonna call either reserve and reject based on the condition that you have here so usually why writing promises guys you may be 80% of you will not deal with writing promises they will deal with consuming promises I'm I'm gonna talk about that later right so this is how you write a promise right it's it's unless you're building api's you're not gonna really write promise but who knows okay so here's what I'm gonna do I'm gonna steal this code here put it inside this func friend and what I'm gonna do is get a number set timeout instead of context if there's nothing called on sexist you call resolve and you pass it anything you want you can't pass it number compares a Jason you can pass it right any anything right so this is exactly now we just wrote a promise okay so what here get the number that's even succeed first do a timeout after a thousand milliseconds resolve it right I'll reject it again and so on okay how do I use that thing guys how do I use this thing are we still recording okay so he told do that too right and do that - doesn't take anything right do that - and here's how we do it do that - returns a promise right so it's an object so you can do dot then right and then expect you to send a function to it is when things are going beautifully right you send a function and we'll call it if things are going everything is good and if anything is a result you call it we'll call that function for you right else it will call catch for you right here's the thing you can call then as many times as you want catch is always once because this wall is one error but you can unlimited call them right so what do we want to do in case of a ten I want to just like we did before just say shock shares promise just make it short and then E is just I just named it a variable you can call it in you can call it whatever you want so you can do this way okay and then in case of an error you do console dot error and then you can do that and then you can do right sweet the statistic that's tested guys refresh refresh and there you go success promise let's refresh again error because it's a odd-even and still it's okay it's not bad right so let's start to complicate things a little bit guys let's say I want to after after things are good I a cold do that again and do something else right so here's what are we gonna do so this function is gonna be current baby because I'm gonna write one more than one line of code so I'm gonna do that I'm gonna success first and then I'm gonna follow it up with return do that too what we'll do what this will do is I call do that you imagine right you'll get a succeed you'll get back here it will call concept like a log succeed that and then we'll call do that too which is in itself it's another promise which will get to return to this thing right so you need to catch that second promise so you can do dog then again right and then you can do essay console the Lord the shock and success baby that's the second success and you can get that number two forgetting the text all right so we can do this way right and if you don't do the curly brace and you just do n do that to that will immediately call that function because essentially what the arrow function does is like if you don't if you have one line of code immediately returns that you don't have to specify a return function okay okay so let's test this thing so what I'm expecting here is so we got unlucky here the first goal was a bad was was an odd number 865 okay so odd there you go success and then fail so this is what happened here what the first call right the first call gave us an even number so we success the first time and then we're called it again which we got a an odd number which called this and we failed right as I'm showing right I want a case where we get to even numbers in a row and essentially this terminates let's try that I want to get that case guys let's believe guys I are let's keep refreshing yes there you go that docked me like at least 10 tries oh my god I'm so unlucky here alright sir the previous video I made it's like it was I got it from the second track but again this is what I got you get an even number we called it again we got a second even number so we we can succeed alright let's talk about finally guys finally is and some of you might already familiar with this would you do try and catch right finally is another part of the promise where you can call also once right it takes a function and what it does is it will call this function for you regardless of whether you have succeeded or you have failed right well you always call this at least one and it's very very very useful especially when you're doing like let's say you're opening a database connection right it's like we have done this we have you actually used it and phosphorus versus JavaScript video I'm gonna reference that in the cards right where we open a cursor here and then we waited and if the six if the cursor is succeeded we can do a query and then after that we're gonna do another query and finally we want to close that cursor to close that connection right so you have to use final in this case to clean up right whether that curse or that connection failed to open you're gonna go to catch and then you want to also close the connection and clean up all right so that it's used for clean up essentially so log let's say finally I'm here alright so if I do will be a fighter issue failed will go finally there you go that's what I want it okay sex is one all right we call it the second time and then finally I'm here alright guys so we talked about callbacks we've got that I talked about promises we talked about finally and finally we're gonna talk about async await now this is one way to do thing right guys bender then the vendor cash right especially if you have like one line of code this is beautiful right so you can't you can literally remove that by the right guys and then this is this is equivalent to that but you're not gonna get the console the login the first one right that's the only difference but what we want to do here is I want to consume this function once you have a promise based function you can consume it this way like we just did and there another way is to consume it with an asynchronous function right let's call this function get a create a function here and you have to create a function for two executed in an async way right and this is how we do it okay and it's called this function app Shakeel right so in this case we just wrote the code in the body but here we have to write function let's go I don't know if she could do that right right and then you have to declare this function as async function okay once you do that what you do is and this is the beauty it will read as if it's synchronous code I'm gonna declare an end variable constant equal do that too but you have to add a weight after it and here's the cool part guys suck sheesh you can just do this way that's one way of doing it right so you can call this sex seed and then immediately you will get her as a result right back so you can what what this will happen is essentially this will wave the result and kinda call then for you and get back the results for you which is this variable end I will send you this variable and put it in this value okay that's what it does essentially so you're gonna get our number essentially and then you what you can do is like literally just write code as you normally do as a synchronous code okay so the problem with this is you have to add a try-catch here okay what Zoe did do is like you do a try and then you do a catch and that catch will capture essentially your you were enter right so let's do a console dot error say ferry older and then let's just do e dear okay and let's execute the code here so obviously we have to call the function because it's just a function right it's just literally called this function and just like take a look at the code guys before we run it so this is this is how are you doing that's another way of doing it using async await so async we'll call this data to do that to get the number primitive good if it's fails if this failed that means you're gonna go to catch let's really go to the cache right and then obviously you can do a finally here and then do a console dot log finally okay you can do whatever you want okay so wait let's listen execute that guy's refresh success a finally failed same thing makes this guy's make sense and now you can just do that or I guess just normally do another dad to get like let's say this is a calling rest endpoint you got back the result the JSON result or the number and then you can do stuff with this right console do it low like this a second call main and then we got in one right and you can do this infinite number of time I'm really torn guys to what is the best approach I like this a lot I think I started using this approach more than that does than does then because this is if you think about this there's a lot there's a lot some ugliness to this I don't know how I feel about that so I'm gonna pass but the question back to you write in the comments section what do you prefer async/await or dot then don't then don't catch the finally or you're an old-school guy or girl that like the callbacks right tell us in the comment section below right that's said the final thing oh actually we actually can debug guys that's and that's a we didn't show that part right but we don't really know to show right but socially you can refresh that success but fail I won't success followed by another success refresh this multiple times there you go second time let's go for a third no let's do it but guys this is how we do the bunny this is debugging definitely async/await once with debugging right so this is like another item we didn't discuss debugging all right so if I do that and I do look at it waits for a second it actually execute that code and waits for a second you get back your number and you can just hover over this and if we're lucky we can actually see the number where's the number five sixteen let's undefined let's do it again and we failed because we got yesterday failed and then we get back the number as e here eight nine 39 and then immediately obviously we can I call this is an error that the browser will treat all right all right guys that's all that's all for us today hope you enjoyed this video if you enjoyed it hit a like subscribe for more cooler stuff and if you if you're having questions about what is the asynchronous versus English I should have sent that in the beginning controller checking out my video here I'm gonna listen listed in the cards a synchronous versus asynchronous what's the difference between the two right so what's that video I I made a video like literally using YouTube as a use case right how the uploading works with YouTube okay and you can you can clearly that I think it's a popular videos up some people like it and what I said I'm gonna see you in the next one you guys stay awesome

Original Description

Promises are Javascript constructs which allow us to perform asynchronous calls without blocking the UX, they are designed for operations that include a lot of waitings such as network requests or timers. In this video we will learn about promise and how we use them coming up in order to discuss promise and why we cme up with them we need to explain how we used to do asynchronous stuff… if you want to learn more about difference between asynchronous and synchronous click this video.. This video explains the async implementation. 0:00 Intro 4:30 callback 8:20 reference http-server 10:45 promises then catch 18:00 finally 18:50 postgres javascript 19:40 async await 25:50 async vs sync Source code https://github.com/hnasr/javascript_playground/tree/master/promisedemo Stay Awesome! Hussein
Watch on YouTube ↗ (saves to browser)
Sign in to unlock AI tutor explanation · ⚡30

Playlist

Uploads from Hussein Nasser · Hussein Nasser · 0 of 60

← Previous Next →
1 Extending ArcObjects (IGeometry) - 01 - Getting Started
Extending ArcObjects (IGeometry) - 01 - Getting Started
Hussein Nasser
2 Extending ArcObjects  (IGeometry) - 02 - The Document, The Map and The Layers
Extending ArcObjects (IGeometry) - 02 - The Document, The Map and The Layers
Hussein Nasser
3 Channel Update - New Book, New Job, New Videos
Channel Update - New Book, New Job, New Videos
Hussein Nasser
4 Learn Programming with VB.NET - 01 - Getting Started
Learn Programming with VB.NET - 01 - Getting Started
Hussein Nasser
5 Learn Programming with VB.NET - 02 - Classes and Objects (Part 1)
Learn Programming with VB.NET - 02 - Classes and Objects (Part 1)
Hussein Nasser
6 Learn Programming with VB.NET - 03 - Classes and Objects (Part 2)
Learn Programming with VB.NET - 03 - Classes and Objects (Part 2)
Hussein Nasser
7 Learn Programming with VB.NET - 04 - User Interface
Learn Programming with VB.NET - 04 - User Interface
Hussein Nasser
8 Learn Programming with VB.NET - 05 - By Value v. By Reference
Learn Programming with VB.NET - 05 - By Value v. By Reference
Hussein Nasser
9 Learn Programming with VB.NET - 06 - Variable size, 32 bit vs 64 bit
Learn Programming with VB.NET - 06 - Variable size, 32 bit vs 64 bit
Hussein Nasser
10 Learn Programming with VB.NET - 07 - Conditional Statements
Learn Programming with VB.NET - 07 - Conditional Statements
Hussein Nasser
11 Learn Programming with VB.NET - 08 - Inheritance
Learn Programming with VB.NET - 08 - Inheritance
Hussein Nasser
12 Learn Programming with VB.NET - 09 - Strategy Design Pattern
Learn Programming with VB.NET - 09 - Strategy Design Pattern
Hussein Nasser
13 Learn Programming with VB.NET - 10 -  How did I learn programming
Learn Programming with VB.NET - 10 - How did I learn programming
Hussein Nasser
14 IGeometry 2016 Retrospective - Channel Update
IGeometry 2016 Retrospective - Channel Update
Hussein Nasser
15 Javascript by Example - The Vook
Javascript by Example - The Vook
Hussein Nasser
16 Vlog - Keep your servers close and your database closer
Vlog - Keep your servers close and your database closer
Hussein Nasser
17 Vlog - Client/Server Programming Languages
Vlog - Client/Server Programming Languages
Hussein Nasser
18 Javascript By Example L1E01 - Getting Started
Javascript By Example L1E01 - Getting Started
Hussein Nasser
19 Persistent Connections (Pros and Cons)
Persistent Connections (Pros and Cons)
Hussein Nasser
20 Javascript By Example L1E02 - Building the Calculator Interface
Javascript By Example L1E02 - Building the Calculator Interface
Hussein Nasser
21 Happy new Year from IGeometry!
Happy new Year from IGeometry!
Hussein Nasser
22 Synchronous v. Asynchronous
Synchronous v. Asynchronous
Hussein Nasser
23 Javascript By Example L1E03 - Displaying the Digits on Calculator Screen
Javascript By Example L1E03 - Displaying the Digits on Calculator Screen
Hussein Nasser
24 Show Your Work. Blog, Vlog, Write, Create and Develop!
Show Your Work. Blog, Vlog, Write, Create and Develop!
Hussein Nasser
25 Relational Database Atomicity Explained By Example
Relational Database Atomicity Explained By Example
Hussein Nasser
26 Javascript By Example L1E04 - Operators, All Clear with Arrow Functions
Javascript By Example L1E04 - Operators, All Clear with Arrow Functions
Hussein Nasser
27 What Comes First, User Experience or Software Architecture?
What Comes First, User Experience or Software Architecture?
Hussein Nasser
28 Javascript By Example L1E05 -  Evaluate the Calculator Expressions with eval
Javascript By Example L1E05 - Evaluate the Calculator Expressions with eval
Hussein Nasser
29 Fastest Way to Learn Programming Language or Technology
Fastest Way to Learn Programming Language or Technology
Hussein Nasser
30 Javascript By Example L1E06 -  Fix Leading Zero Bug with Conditions
Javascript By Example L1E06 - Fix Leading Zero Bug with Conditions
Hussein Nasser
31 Stateful vs Stateless Applications (Explained by Example)
Stateful vs Stateless Applications (Explained by Example)
Hussein Nasser
32 Javascript By Example L1E07 - Running our Calculator on the Mobile Phone
Javascript By Example L1E07 - Running our Calculator on the Mobile Phone
Hussein Nasser
33 Advice for New Software Engineers and Developers
Advice for New Software Engineers and Developers
Hussein Nasser
34 Why JSON is so Popular?
Why JSON is so Popular?
Hussein Nasser
35 Building Scalable Software - SLA, HS, VS
Building Scalable Software - SLA, HS, VS
Hussein Nasser
36 Vlog (Istanbul) - Datacenter Proximity
Vlog (Istanbul) - Datacenter Proximity
Hussein Nasser
37 Should Software Engineers Learn Bleeding-Edge Technologies?
Should Software Engineers Learn Bleeding-Edge Technologies?
Hussein Nasser
38 Do Developers Build Bad User Interfaces/Experience?
Do Developers Build Bad User Interfaces/Experience?
Hussein Nasser
39 Learn By Doing.
Learn By Doing.
Hussein Nasser
40 I Wrote Bad Front-End Code That Broke Chrome
I Wrote Bad Front-End Code That Broke Chrome
Hussein Nasser
41 My Story
My Story
Hussein Nasser
42 Vlog - Horizontal vs Vertical Scaling
Vlog - Horizontal vs Vertical Scaling
Hussein Nasser
43 Can User Experience Help Build Better Rest API?
Can User Experience Help Build Better Rest API?
Hussein Nasser
44 Reverse engineering Instagram in flight mode
Reverse engineering Instagram in flight mode
Hussein Nasser
45 The Benefits of the 3-Tier Architecture (e.g. REST API)
The Benefits of the 3-Tier Architecture (e.g. REST API)
Hussein Nasser
46 Stateless v. Stateful Architecture (Podcast)
Stateless v. Stateful Architecture (Podcast)
Hussein Nasser
47 The evolution from virtual machines to containers
The evolution from virtual machines to containers
Hussein Nasser
48 Proxy vs. Reverse Proxy (Explained by Example)
Proxy vs. Reverse Proxy (Explained by Example)
Hussein Nasser
49 Canary Deployment (Explained by Example)
Canary Deployment (Explained by Example)
Hussein Nasser
50 No Excuses
No Excuses
Hussein Nasser
51 Synchronous vs Asynchronous Applications (Explained by Example)
Synchronous vs Asynchronous Applications (Explained by Example)
Hussein Nasser
52 What is an Asynchronous service?
What is an Asynchronous service?
Hussein Nasser
53 Difference between Client Polling vs Server Push in Notifications
Difference between Client Polling vs Server Push in Notifications
Hussein Nasser
54 Software vs. Hardware AdBlockers (Explained by Example)
Software vs. Hardware AdBlockers (Explained by Example)
Hussein Nasser
55 HTTP Caching with E-Tags -  (Explained by Example)
HTTP Caching with E-Tags - (Explained by Example)
Hussein Nasser
56 Simple Object Access Protocol Pros and Cons (Explained by Example)
Simple Object Access Protocol Pros and Cons (Explained by Example)
Hussein Nasser
57 Nodejs Express "Hello, World"
Nodejs Express "Hello, World"
Hussein Nasser
58 Reverse Engineering Instagram feed
Reverse Engineering Instagram feed
Hussein Nasser
59 Popup Modal Dialog with Javascript and HTML
Popup Modal Dialog with Javascript and HTML
Hussein Nasser
60 MIME and Media Type sniffing explained and the type of attacks it leads to
MIME and Media Type sniffing explained and the type of attacks it leads to
Hussein Nasser

This video tutorial covers the basics of JavaScript Promises and async/await, providing a comprehensive introduction to asynchronous programming in JavaScript. The tutorial covers the use of promises, async/await, and error handling, and provides practical examples and code snippets to illustrate the concepts.

Key Takeaways
  1. Create a new project folder and install Node.js and HTTP-server
  2. Add a script tag to the HTML file and write a function with a callback function
  3. Simulate a network call using setTimeout
  4. Use JavaScript Promises to handle asynchronous operations
  5. Chain promises using then and catch methods
  6. Use finally blocks to execute code regardless of success or failure
  7. Declare a function as async to use async/await syntax
  8. Use try-catch blocks to handle errors in async code
💡 The tutorial highlights the importance of using async/await to handle promises and errors in asynchronous code, and provides practical examples and code snippets to illustrate the concepts.

Related AI Lessons

Chapters (8)

Intro
4:30 callback
8:20 reference http-server
10:45 promises then catch
18:00 finally
18:50 postgres javascript
19:40 async await
25:50 async vs sync
Up next
How to Open HPL Files (HP-GL Plotter)
File Extension Geeks
Watch →