JavaScript Promises Crash Course

  Рет қаралды 37,664

Kevin Powell

Kevin Powell

Күн бұрын

Пікірлер: 100
@teugene
@teugene 4 ай бұрын
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 4 ай бұрын
He does: www.youtube.com/@gomakethings
@aditideshpande3799
@aditideshpande3799 4 ай бұрын
i think he has one already...go make things!
@BienvenidoSantibanez
@BienvenidoSantibanez 4 ай бұрын
the name of his youtube channel is "go make things"
@Uncaught_in_promise
@Uncaught_in_promise 4 ай бұрын
Please please more JavaScript tutorials. This is good stuff always in demand.
@philippkewgvfds2190
@philippkewgvfds2190 2 ай бұрын
bro i just watch this comment and while i do this i fart in my hand and then smell my hand xd the smell is like egg xd its so brutal smell and i still smell it when i writing this comment xd
@LordValtrius
@LordValtrius 4 ай бұрын
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 4 ай бұрын
Because everytime you chain a promise the previous chain returns the answer.
@ittixen
@ittixen 4 ай бұрын
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.
@4ssguard
@4ssguard 2 ай бұрын
After all of struggling with asynchronous JS operations and barely knowing what is going on in those cases Chris finally break the wall of my misunderstanding! Big thank you sir for such a great explanation and thank Kevin as well for all of your work!
@markayyy99
@markayyy99 4 ай бұрын
This was a great explanation and definitely furthered my understanding. Please make more JavaScript videos like this, they help so much. Many thanks!
@tazerah1993
@tazerah1993 4 ай бұрын
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!
@raystorer633
@raystorer633 4 ай бұрын
Kevin, thanks for having Christopher on to explain Javascript promises. He did a great job!
@jfftck
@jfftck 4 ай бұрын
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 4 ай бұрын
You can call async functions inside synchronous ones but you have to register the callback in its scope by calling .then()
@jfftck
@jfftck 4 ай бұрын
@@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 4 ай бұрын
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.
@bryanmyers9977
@bryanmyers9977 4 ай бұрын
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.
@hoshi411
@hoshi411 4 ай бұрын
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 4 ай бұрын
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 4 ай бұрын
@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 4 ай бұрын
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.
@daveturnbull7221
@daveturnbull7221 4 ай бұрын
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.
@jonux13
@jonux13 4 ай бұрын
Thanks kevin and Chris, finally understand promises and async await functions, greetings from Argentina!!
@flpflpflp
@flpflpflp 4 ай бұрын
Really good video, thank you both for taking the time to record it!
@seanprzybyla2157
@seanprzybyla2157 3 ай бұрын
good information generally only thing that i see missing is mention of the onRejected optional method you can pass in with the then. This can let you handle rejections when chaining promises to try and recover the flow instead of just breaking the chain outright. Very rarely used in the wild but its an option and can be useful super basic example. const somePromise = new Promise (doSomething) somePromise .then(handleResolve, handleRejected) .then(doSomeExtraStuff, handleRejected2) .then(doEvenMoreStuff, handleRejected3) .catch(somethingUnrecoverableHappened) .finally(cleanup)
@bobmonsour
@bobmonsour 4 ай бұрын
Today I learned about "finally." Finally! Personally, I prefer the async/await approach as that is how I first began to understand Promises.
@aditideshpande3799
@aditideshpande3799 4 ай бұрын
i genuinely admire you guys for all the knowledge you give us! thanks so much Kevin and Chris! 🎉
@JohnSmith-op7ls
@JohnSmith-op7ls 4 ай бұрын
Async, Await. It’s not the dark ages.
@jfftck
@jfftck 4 ай бұрын
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 4 ай бұрын
@@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 4 ай бұрын
@@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 4 ай бұрын
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 4 ай бұрын
@@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.
@mathiascunault2972
@mathiascunault2972 4 ай бұрын
clear and precise with increasing complexitiy. More stuff like this ! 🙏
@capability-snob
@capability-snob 4 ай бұрын
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 4 ай бұрын
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 4 ай бұрын
@@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.
@osamudiameh_sama
@osamudiameh_sama 4 ай бұрын
I pumped my fist when I saw the notification,promises been giving me a tough time. Thanks for this kev
@whatisthis__95
@whatisthis__95 4 ай бұрын
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
@modi_hemnt77
@modi_hemnt77 4 ай бұрын
Loved this tutorial!! Please more of this.
@MrTheoJ
@MrTheoJ 4 ай бұрын
Absolute amazing tutorial
@KB04
@KB04 4 ай бұрын
Please, im begging, i hope you do more javascript videos when you have time.
@fatimanura6359
@fatimanura6359 4 ай бұрын
JS tutorial from sir kevin powell!!??? No Way!!!, Thank you So much
@bbrixon
@bbrixon 4 ай бұрын
My eyes are glazing over, but that's wonderful. This might get me to finally take some JS courses.
@CheeseSteaksJimmy-g4l
@CheeseSteaksJimmy-g4l 4 ай бұрын
Wow this was super useful and explained in the best way
@adampielach4942
@adampielach4942 4 ай бұрын
Bright color mode is literally a felony
@friendly__drone9352
@friendly__drone9352 4 ай бұрын
Great video Kevin! (There's a slight typo in the title "Promsises")
@nustaniel
@nustaniel 4 ай бұрын
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)
@thecodeartisan
@thecodeartisan 4 ай бұрын
Thank you for this video. As always, the BEST of the BEST.
@TheMetalMag
@TheMetalMag 4 ай бұрын
I wish I had this video 2 years ago.. thanks
@Web-Dev-Codi
@Web-Dev-Codi 4 ай бұрын
Spelling promises
@ideallyyours
@ideallyyours 4 ай бұрын
@@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 4 ай бұрын
He promises to fix it
@Web-Dev-Codi
@Web-Dev-Codi 4 ай бұрын
@@ideallyyours we are just making sure he knows what's happening and I'm sure he appreciates the feedback.
@rahmanmusah4470
@rahmanmusah4470 4 ай бұрын
@@georgeliss4015😂😂😂😂
@rahmanmusah4470
@rahmanmusah4470 4 ай бұрын
@@DavidBrown-bs7ggI'm putting this comment in a museum 😂😂
@playfulsparklestudio
@playfulsparklestudio 4 ай бұрын
This is super useful, thank you 🙏❤️
@rajunaidu7751
@rajunaidu7751 4 ай бұрын
First I smoke this CSS and then I smoke this JavaScript
@dipakdayanand
@dipakdayanand 3 ай бұрын
So, a promise object is created by passing a callback function and the arguments for the callback function are functions themselves ? Did I get it right ?
@elhamzeinodini4828
@elhamzeinodini4828 4 ай бұрын
Thanks for js content, it's as good as your css ones
@VladyslavHaidar
@VladyslavHaidar 4 ай бұрын
What framework is Chris using for daily development?
@LinhTran-om6qh
@LinhTran-om6qh Ай бұрын
One thing I'm still trying to wrap my head around is why the executor function can have access to resolve and reject method. I get that when creating a new promise, I need to pass an executor function. What I don't understand is why I have access to reject and resolve from the executor while I am the one who creates the executor itself? I know there are reject and resolve methods inside the promise constructor, and these two methods are passed to the executor as arguments at the end of the constructor and the executor gets executed immediately. But doesn't that mean I both provide the executor and also receive the executor from the constructor? It seems so circular to me...
@adolfomartin5456
@adolfomartin5456 4 ай бұрын
Promise constructor is not new, it is a lot old. Async-await is sugar syntax for promises.
@servertimeout8371
@servertimeout8371 4 ай бұрын
dark mode please for code. it's too bright
@MondisCrow
@MondisCrow 4 ай бұрын
This was excellent!
@maikwolfram
@maikwolfram 4 ай бұрын
Thank u sooooooooo much for this channel !!!
@karima746
@karima746 2 ай бұрын
excellent thank you
@prajapati_dp
@prajapati_dp 4 ай бұрын
Well explained
@27sosite73
@27sosite73 4 ай бұрын
ty mate
@mad_circuits
@mad_circuits 4 ай бұрын
My world is being destroyed. CSS god is doing JavaScript! The end is near!
@alexandrmeyer
@alexandrmeyer 4 ай бұрын
wow, who is the guy and where is his channel?
@lucassomething8653
@lucassomething8653 4 ай бұрын
Is Chris like Arnold Schwarzenegger in Last action hero? Because he wears the same shirt in every film 😉
@deatho0ne587
@deatho0ne587 4 ай бұрын
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.
@k16e
@k16e 4 ай бұрын
"Promises are weird"... JavaScript mimicking real life.
@chumager
@chumager 3 ай бұрын
pta mare... pensé que el tío Kevin iba a enseñar promesas, sólo quería reírme un rato :ó(
@michaelgoddard4122
@michaelgoddard4122 4 ай бұрын
Just starting JS so this is still above my pay scale.😢
@proteus1
@proteus1 4 ай бұрын
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 4 ай бұрын
I wish you would go deeper, great video, but a bit basic
@truthteachers
@truthteachers 4 ай бұрын
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.
@Steel0079
@Steel0079 4 ай бұрын
Prom sises?
@skygnd
@skygnd 4 ай бұрын
💀
@3dxspx703
@3dxspx703 4 ай бұрын
You're like, 5 yrs late with this topic sir.
@skygnd
@skygnd 4 ай бұрын
Prom sis 💀
@JosephCodette
@JosephCodette 4 ай бұрын
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 4 ай бұрын
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.
@abhishekganapure6456
@abhishekganapure6456 4 ай бұрын
kevin all the way 🫡👍
@philliplam2704
@philliplam2704 4 ай бұрын
Promises are 1999 wtf is wrong with you just use Async await Jesus
The different types of JavaScript functions explained
14:47
Kevin Powell
Рет қаралды 43 М.
UFC 308 : Уиттакер VS Чимаев
01:54
Setanta Sports UFC
Рет қаралды 932 М.
Smart Sigma Kid #funny #sigma
00:14
CRAZY GREAPA
Рет қаралды 103 МЛН
Mia Boyka х Карен Акопян | ЧТО БЫЛО ДАЛЬШЕ?
1:21:14
Что было дальше?
Рет қаралды 8 МЛН
A new approach to container and wrapper classes
25:27
Kevin Powell
Рет қаралды 266 М.
5 Signs of an Inexperienced Self-Taught Developer (and how to fix)
8:40
Center the bottom row when using grid auto-fit
26:54
Kevin Powell
Рет қаралды 9 М.
JavaScript Promises  -- Tutorial for Beginners
37:05
ColorCode
Рет қаралды 130 М.
Write less code with these 5 CSS tips
15:38
Kevin Powell
Рет қаралды 49 М.
Relative colors make so many things easier!
13:16
Kevin Powell
Рет қаралды 51 М.
My top 5 most popular front-end tips
22:07
Kevin Powell
Рет қаралды 52 М.
Async Await vs. Promises - JavaScript Tutorial for beginners
24:30
How to take control of Flexbox
16:01
Kevin Powell
Рет қаралды 140 М.
Avoid these 5 beginner CSS mistakes
21:38
Kevin Powell
Рет қаралды 86 М.
UFC 308 : Уиттакер VS Чимаев
01:54
Setanta Sports UFC
Рет қаралды 932 М.