JavaScript Promises Crash Course

  Рет қаралды 30,190

Kevin Powell

Kevin Powell

Күн бұрын

Links to all the code and more of Chris' great content: gomakethings.com/kevinpowell/
⌚ Timestamps
00:00 - Introduction
01:40 - Creating a promise
03:50 - Errors and catch
05:20 - Chaining multiple methods
07:42 - Using finally
08:54 - Practical examples
14:05 - async and await
16:45 - gotchas with async and await
22:00 - Which approach should you use?
#css
--
Come hang out with other dev's in my Discord Community
💬 / discord
Keep up to date with everything I'm up to
✉ www.kevinpowell.co/newsletter
Come hang out with me live every Monday on Twitch!
📺 / kevinpowellcss
---
Help support my channel
👨‍🎓 Get a course: www.kevinpowell.co/courses
👕 Buy a shirt: teespring.com/stores/making-t...
💖 Support me on Patreon: / kevinpowell
---
My editor: VS Code - code.visualstudio.com/
---
I'm on some other places on the internet too!
If you'd like a behind the scenes and previews of what's coming up on my KZbin channel, make sure to follow me on Instagram and Twitter.
Twitter: / kevinjpowell
Codepen: codepen.io/kevinpowell/
Github: github.com/kevin-powell
---
And whatever you do, don't forget to keep on making your corner of the internet just a little bit more awesome!

Пікірлер: 93
@BMikel
@BMikel 19 күн бұрын
Please please more JavaScript tutorials. This is good stuff always in demand.
@teugene
@teugene 19 күн бұрын
I wish Chris has a KZbin channel with lessons like this. The way he explains JS is so easy to absorb and understand.
@Killyspudful
@Killyspudful 19 күн бұрын
He does: www.youtube.com/@gomakethings
@aditideshpande3799
@aditideshpande3799 17 күн бұрын
i think he has one already...go make things!
@LordValtrius
@LordValtrius 19 күн бұрын
One thing that was skirted around but not touched on is that a promise saved to a variable but isn't chained will cache it's value for future then's, making it perfect for caching since most caches only check if the value exists and sends another request, not if the value is being fetched. Eg: const question = Promise.resolve(42) question.then(answer => console.log(answer)) question.then(answer => console.log(answer)) You get 42 logged twice, but if you were to chain them instead, the second would log undefined since nothing is returned from the first. Great video too, keep it up.
@asagiai4965
@asagiai4965 17 күн бұрын
Because everytime you chain a promise the previous chain returns the answer.
@raystorer633
@raystorer633 19 күн бұрын
Kevin, thanks for having Christopher on to explain Javascript promises. He did a great job!
@mathiascunault2972
@mathiascunault2972 11 сағат бұрын
clear and precise with increasing complexitiy. More stuff like this ! 🙏
@tazerah1993
@tazerah1993 19 күн бұрын
Chris is a great teacher, but I'd love to see you engage more in the topic when you have guests on! Maybe re-contextualize the subject in a way that was helpful for you, or ask questions that you think a beginner might ask. Love the videos, Kevin. Thanks!
@flpflpflp
@flpflpflp 17 күн бұрын
Really good video, thank you both for taking the time to record it!
@bryanmyers9977
@bryanmyers9977 19 күн бұрын
I'm really loving these JavaScript videos. The timing is perfect for me because I'm refreshing my skills before going out for a job. Chris is one of the best teachers I've ever seen for this. Very organized and clearly communicated.
@markayyy99
@markayyy99 16 күн бұрын
This was a great explanation and definitely furthered my understanding. Please make more JavaScript videos like this, they help so much. Many thanks!
@jonux13
@jonux13 11 күн бұрын
Thanks kevin and Chris, finally understand promises and async await functions, greetings from Argentina!!
@aditideshpande3799
@aditideshpande3799 17 күн бұрын
i genuinely admire you guys for all the knowledge you give us! thanks so much Kevin and Chris! 🎉
@modi_hemnt77
@modi_hemnt77 13 күн бұрын
Loved this tutorial!! Please more of this.
@daveturnbull7221
@daveturnbull7221 19 күн бұрын
Saw the title of this and instantly started preparing my braincell to be blown away. This is a topic I've struggled with from the moment they were introduced.
@osamudiameh_sama
@osamudiameh_sama 19 күн бұрын
I pumped my fist when I saw the notification,promises been giving me a tough time. Thanks for this kev
@hoshi411
@hoshi411 18 күн бұрын
I love that you are doing these javascript dives but if I wanted a dictionary definition of these things , I can just read a dictionary. This didn't answer the questions that I needed answered for me to actually understand promises. I needed him to explain what people did before promises existed. How did they get stuff done without a promise style function and how did promises then improve their life using examples. I also needed to get more real world situations where a developer comes across an issue and thinks, "this is exactly where I should use a promise." I write javascript web apps myself and I have never used a promise. Should I be using them? Why , if I am already living life without them? How can they help me. He needed to show code solutions without promises and then show the problematic nature of that and then bring along the hero "dun dda da dan !!! The Promise!" and show how that brings light to the problem. All he does in these videos is read from a dictionary of what a promise is. that is not helpful. Please make the video again but do it in the format that I have suggested here.
@dealloc
@dealloc 18 күн бұрын
What we did (and still do) was using events and callbacks. In other cases it would be blocking, like XMLHttpRequest before `fetch` API.
@DanielGrima90
@DanielGrima90 16 күн бұрын
@hoshi411 I would suggest reading a bit about JavaScript "Callback Hell" which sometimes is also called the "Pyramid of Doom". This should give you a very good idea why Promises were created and why they are used. Most times the fetch API is used to showcase Promises and API calls. However in the JavaScript world nowadays where before we used callback functions we now have Promises. This is not to say that callbacks aren't used, they still are, but if your code is asynchronous Promises are recommended. They are easier to read, maintain and handle errors better :)
@stephaniepeters2590
@stephaniepeters2590 13 күн бұрын
How are you handling API requests then? Are you still using XMLHTTPRequest? Or a library such as axios (in which case I guess you would in fact be using Promises) To be fair, fetch is the perfect example, though. Another one is animating and awaiting animation end with JS, or anything that needs to await browser rendering, if you want to avoid the setTimeout hack.
@thecodeartisan
@thecodeartisan 19 күн бұрын
Thank you for this video. As always, the BEST of the BEST.
@jfftck
@jfftck 19 күн бұрын
If you ever hear someone talking about a function’s color, it is just saying that asynchronous and synchronous functions are a different “color” and you can only use synchronous functions inside asynchronous ones, but not the other way around. It is just easier to remember that async doesn’t return a value directly, so to wait for it, but to be able to do anything else, you will also need to wait for the parent function as well, all the way until the top function is reached. This is one of the most common issues new developers encounter and have difficulty with understanding. This video didn’t explain how asynchronous functions work inside the JavaScript runtime, but the simple explanation is that there are three ways functions return a value: just calling a regular, callback for an event, or resolving a promise. So, there is a loop that checks stacks for code to run and it has to check three of them, the first stack is ran immediately, and the next two are added to the first when the condition has been met - like the event being triggered or the promise resolved/rejected. That is why you can’t call asynchronous functions inside synchronous ones, they don’t exist yet in the stack and will only exist after the next iteration of the loop.
@maciejzettt
@maciejzettt 19 күн бұрын
You can call async functions inside synchronous ones but you have to register the callback in its scope by calling .then()
@jfftck
@jfftck 18 күн бұрын
@@maciejzettt You pass a callback into the then, and it still is called after the function exists, try putting a message in an element on the page or out to the console inside the then and just before leaving the function, it will be the message you put in just before exiting the function that will be displayed first. You are no longer coloring the function, but it is still out of order execution, which is the only way to use the promise inside of a regular function.
@maciejzettt
@maciejzettt 18 күн бұрын
I agree with you when it comes to the outcome and internals, but you technically call that async function, i.e., initiate its execution from within the sync one. It's just that the following code outside of the callback doesn't wait for the result. And it doesn't wait only if the resolution of the async function waits for results from outside of the JS engine, otherwise, as you said, the function runs until it returns and blocks the event loop. It's only a conceptual thing as there's no point in writing such heavy-working functions as asynchronous or even writing them in JS at all. I wanted to show that although completely wrong and nasty, you can imagine such async function which could be called and even completed in the lifetime of the outer synchronous function's scope.
@adampielach4942
@adampielach4942 16 күн бұрын
Bright color mode is literally a felony
@whatisthis__95
@whatisthis__95 17 күн бұрын
I don't know why people keep saying in tutorials that applying the .json() method to a response (for example) gives you a JSON object, when actually it returns a JS object (plain old regular object). That must confuse a lot of people
@JohnSmith-op7ls
@JohnSmith-op7ls 19 күн бұрын
Async, Await. It’s not the dark ages.
@jfftck
@jfftck 18 күн бұрын
It depends on your needs, but generally use the async function before using then, as most developers find it easier to reason about.
@JohnSmith-op7ls
@JohnSmith-op7ls 18 күн бұрын
@@jfftck Maybe there’s some rare or contrived case where a promise is better but I’ve yet to see one and there’s a reason why other languages never went down that path and just implemented the async and await syntax. I have’t seen a case in those languages where you’d want or need a promise syntax. Promises do the same thing but are overly verbose and often lead to nesting issues which cause maintenance, debugging, and readability headaches.
@rockatanescu
@rockatanescu 18 күн бұрын
@@JohnSmith-op7ls I think it's much better that they started with Promise and then moved to async/await. I am fairly certain that most people writing JS/TS code nowadays don't really understand what async/await do.
@dealloc
@dealloc 18 күн бұрын
Async/await is not mutually exclusive with Promises. Async/await is just syntatic sugar for Promise control flow. There is no "promise syntax". Promise is the API, async/await + try/catch is the control flow to deal with promises. Other languages implements the same concept; have an API (i.e. "Futures" or "Task") and provide syntax to handle the control flow (async fn / do_thing().await, await doThing(), etc.). You're still dealing with those things under the hood-you don't get to choose.
@JohnSmith-op7ls
@JohnSmith-op7ls 18 күн бұрын
@@dealloc I mean, above bytecode, it’s all “syntactic sugar”. Semantics aside, the point is, why use a more verbose, more difficult to read and maintain way to accomplish async coding when you don’t have to. Where’s the benefit? Working directly with threads is a pain so you need a good reason to. JS doesn’t give you that option so you’ve got two ways of telling the JS engine to do async control flow, why not use the simpler one.
@user-ix5vf8wu1i
@user-ix5vf8wu1i 15 күн бұрын
Wow this was super useful and explained in the best way
@KB04
@KB04 19 күн бұрын
Please, im begging, i hope you do more javascript videos when you have time.
@playfulsparklestudio
@playfulsparklestudio 18 күн бұрын
This is super useful, thank you 🙏❤️
@ittixen
@ittixen 19 күн бұрын
I love those. I was hoping he'd mention how promises returned from another promise kinda automagically get then()'ed, because it really tripped me up when I was first learning promises, and honestly I still to this day didn't manage to wrap my head around it.
@MrTheoJ
@MrTheoJ 3 күн бұрын
Absolute amazing tutorial
@bobmonsour
@bobmonsour 16 күн бұрын
Today I learned about "finally." Finally! Personally, I prefer the async/await approach as that is how I first began to understand Promises.
@MondisCrow
@MondisCrow 19 күн бұрын
This was excellent!
@maikwolfram
@maikwolfram 19 күн бұрын
Thank u sooooooooo much for this channel !!!
@bbrixon
@bbrixon 19 күн бұрын
My eyes are glazing over, but that's wonderful. This might get me to finally take some JS courses.
@capability-snob
@capability-snob 18 күн бұрын
I appreciate that he says "a promise that something will happen" and not "a promise of a future value". Why? The motivation for promises was this: Alice sends a parts list to Bob and requests that when he is done, he send the bill to Carol in accounting. In a threaded environment, Alice would need to stand around twiddling her thumbs until Bob replied, and then she'd send the result to Carol. Promises are the fundamental unit of "when this completes, do that". I really liked Hallie's tutorial on promises, but the original is pretty good, too: Mark Miller's PhD thesis. Promises fit a lot better into the E programming language, used in the thesis, than they do in JavaScript, and E makes pretty clear what problems promises were designed to solve.
@dealloc
@dealloc 18 күн бұрын
What you are describing is not unique to Promises. In fact, events and callbacks are suited for this type of non-blocking flow as well and is what was the _only_ way to do it before promises were introduced. But are not a deprecated way of dealing with asynchronous code. The introduction of promises were more of an technical one; to allow tasks with higher prioritisation than other tasks in the event loop. setTimeout and setInterval are examples of tasks that are created in a macro task queue, whereas promises are created within the micro task queue. If there are any tasks in the micro task queue, those will be executed before the next task in the macro task queue. Apart from nextTick from Node.js, promise callbacks will always be executed before other callbacks. This was also a time before async/await to block execution in a separate flow, while waiting for a promise to fulfil or reject. Previously you'd have to place your code depending on those results inside those callbacks.
@capability-snob
@capability-snob 17 күн бұрын
@@dealloc If you've followed the "prior art" links from the promises/a+ spec, you will note that none of the prior art matched the prioritisation given by the micro task queue. In fact, prioritisation was an open question in the previous "a spec". A+ included a fix to be specific that functions passed to then() do not execute immediately. So in fact, there was a lot of interest in promises, regardless of the priority of the enqueued tasks. If that was news to you, you might enjoy looking up the names in the credits of the spec. I mentioned Mark Miller, who had described in detail the specific semantics that made it into javascript way back in the 90s, but also Kris Kowal, who arguably did the first port to javascript from the original E description.
@prajapati_dp
@prajapati_dp 19 күн бұрын
Well explained
@friendly__drone9352
@friendly__drone9352 18 күн бұрын
Great video Kevin! (There's a slight typo in the title "Promsises")
@Web-Dev-Codi
@Web-Dev-Codi 19 күн бұрын
Spelling promises
@georgeliss4015
@georgeliss4015 19 күн бұрын
Made you comment tho :) Intentional typos = the oldest trick in the book
@ideallyyours
@ideallyyours 19 күн бұрын
@@georgeliss4015 Sure, but a comment section with actual content discussion adds more value to the video than one pointing out silly mistakes.
@DavidBrown-bs7gg
@DavidBrown-bs7gg 19 күн бұрын
He promises to fix it
@farhan-app
@farhan-app 19 күн бұрын
I think he’s dyslexic, so it’s a pretty good attempt!
@Web-Dev-Codi
@Web-Dev-Codi 18 күн бұрын
@@ideallyyours we are just making sure he knows what's happening and I'm sure he appreciates the feedback.
@fatimanura6359
@fatimanura6359 17 күн бұрын
JS tutorial from sir kevin powell!!??? No Way!!!, Thank you So much
@27sosite73
@27sosite73 8 күн бұрын
ty mate
@TheMetalMag
@TheMetalMag 18 күн бұрын
I wish I had this video 2 years ago.. thanks
@elhamzeinodini4828
@elhamzeinodini4828 19 күн бұрын
Thanks for js content, it's as good as your css ones
@nustaniel
@nustaniel 19 күн бұрын
I like the "async function ()" declaration approach more since it also declares very clearly in your code that you are doing an asynchronous function. You don't need to look at the body of the function to understand and identify immediately that it is an async function. Also I guess JavaScript is going to Prom with its sises? (Original video title: JavaScript Promsises Crash Course)
@servertimeout8371
@servertimeout8371 18 күн бұрын
dark mode please for code. it's too bright
@rajunaidu7751
@rajunaidu7751 19 күн бұрын
First I smoke this CSS and then I smoke this JavaScript
@user-hd8dm5ur3i
@user-hd8dm5ur3i 16 күн бұрын
What framework is Chris using for daily development?
@adolfomartin5456
@adolfomartin5456 18 күн бұрын
Promise constructor is not new, it is a lot old. Async-await is sugar syntax for promises.
@lucassomething8653
@lucassomething8653 19 күн бұрын
Is Chris like Arnold Schwarzenegger in Last action hero? Because he wears the same shirt in every film 😉
@michaelgoddard4122
@michaelgoddard4122 16 күн бұрын
Just starting JS so this is still above my pay scale.😢
@deatho0ne587
@deatho0ne587 19 күн бұрын
What if a response should be JSON if 200, but if 204 or some other 200 series returns just a simple "string". I get how to do it, but might work for another video on top of this one. To be fair to the above what goes across the wire is never JSON.
@alexandrmeyer
@alexandrmeyer 16 күн бұрын
wow, who is the guy and where is his channel?
@k16e
@k16e 18 күн бұрын
"Promises are weird"... JavaScript mimicking real life.
@mad_circuits
@mad_circuits 17 күн бұрын
My world is being destroyed. CSS god is doing JavaScript! The end is near!
@proteus1
@proteus1 19 күн бұрын
Off topic, but is there any easy work from home laptop jobs I caould do or learn as i want to get away from being tradesman. i KNOW HTML AND MODERATE CSS
@galangel8287
@galangel8287 13 күн бұрын
I wish you would go deeper, great video, but a bit basic
@Steel0079
@Steel0079 19 күн бұрын
Prom sises?
@skygnd
@skygnd 19 күн бұрын
💀
@truthteachers
@truthteachers 14 күн бұрын
Hi, all this simply because of Javascript being dysfunctional in the way it executes the code. Perhaps its a better time now that Javascript should be dumped and a new language structure to be created. Javascript is like an old Corvette adding on additional parts to make it look run like a Porche. Especially when they keep adding more junks like es6 and es2017. Very sloppy code.
@skygnd
@skygnd 19 күн бұрын
Prom sis 💀
@3dxspx703
@3dxspx703 19 күн бұрын
You're like, 5 yrs late with this topic sir.
@JosephCodette
@JosephCodette 18 күн бұрын
So sad to see to see you caved into doing JS videos , and not even done by you, which makes it even worse.
@rossclutterbuck1060
@rossclutterbuck1060 19 күн бұрын
Honestly, there was nothing wrong with XmlHttpRequest, and arguably Promise use more callbacks than the "callback hell" people cried about thinking XHR was bad. Async await is nice though.
@philliplam2704
@philliplam2704 15 күн бұрын
Promises are 1999 wtf is wrong with you just use Async await Jesus
@abhishekganapure6456
@abhishekganapure6456 15 күн бұрын
kevin all the way 🫡👍
The different types of JavaScript functions explained
14:47
Kevin Powell
Рет қаралды 37 М.
23 CSS features you should know (and be using) by now
31:31
Kevin Powell
Рет қаралды 64 М.
My little bro is funny😁  @artur-boy
00:18
Andrey Grechka
Рет қаралды 11 МЛН
Василиса наняла личного массажиста 😂 #shorts
00:22
Денис Кукояка
Рет қаралды 9 МЛН
We Got Expelled From Scholl After This...
00:10
Jojo Sim
Рет қаралды 74 МЛН
Interview with Senior JS Developer 2024 [NEW]
6:45
Programmers are also human
Рет қаралды 460 М.
JavaScript var, let, and const explained
11:56
Kevin Powell
Рет қаралды 21 М.
Can you build a web app with vanilla Web Components in 2024?!?
30:16
Go Make Things
Рет қаралды 3,6 М.
The Most Important Skill You Never Learned
34:56
Web Dev Simplified
Рет қаралды 165 М.
We can now transition to and from display: none
21:20
Kevin Powell
Рет қаралды 73 М.
10 Nooby Mistakes Devs Often Make In Python
24:31
Indently
Рет қаралды 46 М.
Looking Under the Hood of JavaScript
6:34
ThePrimeagen
Рет қаралды 178 М.
Avoid these 5 beginner CSS mistakes
21:38
Kevin Powell
Рет қаралды 73 М.
Every React Concept Explained in 12 Minutes
11:53
Code Bootcamp
Рет қаралды 428 М.