You're using Javascript Promises The wrong way

  Рет қаралды 56,375

CoderOne

CoderOne

Жыл бұрын

🧭 Build Login/Register API Server w/ Authentication | JWT Express AUTH using Passport.JS and Sequelize
• Build Login/Register A...
🧭 Turn Design into React Code | From prototype to Full website in no time
• Turn Design into React...
🧭 Watch Tutorial on Designing the website on Figma
• I Design a onecolor We...
🧭 Watch Create a Modern React Login/Register Form with smooth Animations
• Create a Modern React ...
🧭 Debug React Apps Like a Pro | Master Debugging from Zero to Hero with Chrome DevTools
• Debug React Apps Like ...
🧭 Master React Like Pro w/ Redux, Typescript, and GraphQL | Beginner to Advanced in React
• Master React Like Pro ...
🧭 Learn Redux For Beginners | React Redux from Zero To Hero to build a real-world app
• Debug React Apps Like ...
🧭 Introduction to GraphQL with Apollo and React
• Introduction to GraphQ...
🐦 Follow me on Twitter: / ipenywis
💻 Github Profile: github.com/ipenywis
Made with 💗 by Coderone

Пікірлер: 82
@joelm2858
@joelm2858 Жыл бұрын
6:04 - There's no reason to create those extra variables for productsPromise and categoriesPromise. Just do `const [products, categories] = await Promise.all([fetchProducts(), fetchCategories()])`
@sheldonfourie5959
@sheldonfourie5959 Жыл бұрын
MVP guy
@yaroslavqwerty8609
@yaroslavqwerty8609 Жыл бұрын
Agree, and what if there is an error in request, will array destructuring work?
@joelm2858
@joelm2858 Жыл бұрын
@@yaroslavqwerty8609 you need to wrap a promise all in a try catch since promise all returns an error if one of the promises fail. Check MDN for full example
@Friskni
@Friskni Жыл бұрын
.allSettled anyone? nope? ok
@ibnShafee
@ibnShafee Жыл бұрын
Yes, I was thinking the same
@BogacGuven
@BogacGuven Жыл бұрын
A good reminder about promises' not so intuitive use-case. 👍 If anyone didn't get it from this video I'd also recommend Dave Gray's video "Callbacks, Promises, Async Await | JavaScript Fetch API Explained". Specifically a very similar example is at t:37:06. I'd recommend to watch that video from the beginning if you still didn't get why this happens.
@faythe03
@faythe03 Жыл бұрын
That's very insightful, for when the data between the promises is not always dependant
@MrShaheer
@MrShaheer Жыл бұрын
thats great knowledge thank you for sharing it. FYI: you could speed up and run getProductsByCategory by just making another API to get productsbyTopCategory, the API should calculate the top category on the server side (or use a cached version generated by previous call of getCategories) and just return products by that category, that way all three requests would go at the same time.
@ukaszzbrozek6470
@ukaszzbrozek6470 Жыл бұрын
Instead of using Promise.all you should use Promise.allSettled. Promise.all if any error occurred would throw only the first failed request error. With Promise.allSettled you can show to the user at least partial data and console log for the programmer all problems with the BE.
@hojdog
@hojdog Жыл бұрын
Yeah, basically depends on what you want it to do. Sometimes you want it to error out because you won’t use the results of the others of one of them fails. Also note with allSettled - if you don’t care if some of them fail but you still want to know; I always use it in a quick helper function that logs all the failed requests, otherwise it can be hard to debug.
@ukaszzbrozek6470
@ukaszzbrozek6470 Жыл бұрын
@@hojdog I think it still better to hold to data that you get and retry only failed promises then retrying everything. After failed you should retry.
@esequielalbornoz5271
@esequielalbornoz5271 Жыл бұрын
The issue with this approach is that if the products API takes 2 seconds and the categories take only 500ms, you won't be able to access the result of the categories until the products API returns the response
@esequielalbornoz5271
@esequielalbornoz5271 Жыл бұрын
I would use something like this (if react query is not available) fetchProducts() .then(resp => resp.json()) .then(products => setProducts(products)) fetchCategories() .then(resp => resp.json()) .then(categories => setCategories(categories))
@osquigene
@osquigene Жыл бұрын
​@@esequielalbornoz5271 or you could just write two async functions to fetch + set states and resolve them in parallel. That would avoid that uggly mess of "thens".
@huncho6295
@huncho6295 Жыл бұрын
Thanks for sharing your experience on handling async fetching
@focusiam2027
@focusiam2027 Жыл бұрын
Hello, thank you for this tutorial. Do you have the video where you build this app?
@shivangm24
@shivangm24 Жыл бұрын
Got to learn new way to optimize for parallel use cases. Tanks!!
@rajaj6043
@rajaj6043 Жыл бұрын
Thanks for sharing, Nice tips!!!
@MF-hx8or
@MF-hx8or Жыл бұрын
It was wonderful, thank you 😍😍😍
@jorgericaldi6438
@jorgericaldi6438 Жыл бұрын
i have question. You need to wait anyway for products before categories, of course that is faster now because the promise.all or the other way, but is still waiting for products first. So will it be a best solution just move every call on his own useEffect even productsByCategory(with dependencies) ?
@harrisonekpobimi4764
@harrisonekpobimi4764 Жыл бұрын
Insightful. Thanks
@ayoub.k
@ayoub.k Жыл бұрын
Hey man, I understand the need for using click bait titles, but that has a negative impact on junior or beginner developers. You say people are using something wrong, then you skip over use cases where the approach you say is wrong might actually be the best approach, and then you process to explain the better way which isn't the better way at all in some certain scenarios. I commented on another video of yours that anything has its own use case, so, please do better research and present a well rounded explanation in your videos in the future. Peace.
@ych3455
@ych3455 Жыл бұрын
Could you explain when it is bad to use this approach
@ayoub.k
@ayoub.k Жыл бұрын
@@ych3455 in some usecases, the second promise will be dependant on data being resolved by the first promise, in this case sequential promises make sense.
@n_cruz144
@n_cruz144 Жыл бұрын
In his defense, he goes over that they're not dependent on each other and could run in parallel... highlighting the use case scenario at about 3:40
@ayoub.k
@ayoub.k Жыл бұрын
@@n_cruz144 this is supposed to be an educational channel, the click bait title plus the lack of clear information gives the video an F
@akshayhere
@akshayhere Жыл бұрын
@@ayoub.k He clearly stated it.
@creayt
@creayt Жыл бұрын
This video took 10 minutes to explain a 30 second concept, well done
@K.Huynh.
@K.Huynh. Жыл бұрын
thank for sharing!
@humansaremortal3803
@humansaremortal3803 Жыл бұрын
How do I setup "loading" with this way of coding?
@osquigene
@osquigene Жыл бұрын
That's literally the first thing you would learn about asynchronous programming so I doubt people would not know about this.
@ThiagoLucioBittencourt
@ThiagoLucioBittencourt Жыл бұрын
Amazing examples. Open knowledge about. Thanks to share.this
@noriller
@noriller Жыл бұрын
Last case, if possible, would try to have a backend API doing that.
@lamargtv2572
@lamargtv2572 Жыл бұрын
Amazing!
@AngusMcIntyre
@AngusMcIntyre Жыл бұрын
In real life, seperate components would load both payloads. You won't see this category of error for ajax data loading in a properly architected app. The TLDR should be "only schedule a continuation if you depend upon the prior operation"
@eony
@eony Жыл бұрын
that's pretty cool, thanks.
@yadneshkhode3091
@yadneshkhode3091 Жыл бұрын
thanks man
@yolopolo5783
@yolopolo5783 Жыл бұрын
Can't we just create two seperate async functions
@irfanmohammad7269
@irfanmohammad7269 Жыл бұрын
Nice content
@utkukemalcifci9525
@utkukemalcifci9525 Жыл бұрын
Thanks :)
@letri8757
@letri8757 Жыл бұрын
I don't think it's a wrong way: 1. sometime u need to sequential (line by line for api dependency). 2. promise is run by the way it's created (sequential & parallel).
@EhteshamShahzad
@EhteshamShahzad Жыл бұрын
You didn't watch the entire video
@letri8757
@letri8757 Жыл бұрын
​@@EhteshamShahzad yup i didn't because this is not the wrong way :).
@EhteshamShahzad
@EhteshamShahzad Жыл бұрын
​@@letri8757 you should. and then revisit your comment
@letri8757
@letri8757 Жыл бұрын
@@EhteshamShahzad sorry nope :)
@EhteshamShahzad
@EhteshamShahzad Жыл бұрын
@@letri8757 you must be a fun colleague to work with :)
@Lindaine
@Lindaine Жыл бұрын
Isn't this concurrency instead of parallel?
@caiyuhui
@caiyuhui Жыл бұрын
I think code lines"const procuctsPromise=fetchProducts();const products=await productsPromises;" have someting to do with "javascript hoisting". Firstly , variable productsPromise is hoisted in TDZ;secondly,productsPromise is initialized with a value(actually the function fetchProducts()),and this is the key point cause this process can be parallelized;Finally, the parallel execution of applying the await operator to yet another variable productsPromise(avoid directly applying to a sync function) .
@popuguytheparrot_
@popuguytheparrot_ Жыл бұрын
Sooo, what about promises?
@sinapiranix
@sinapiranix Жыл бұрын
best video👌👌
@sogggy
@sogggy Жыл бұрын
Noice!
@SuperNZY
@SuperNZY Жыл бұрын
GJ!
@orielsy
@orielsy Жыл бұрын
I would have loved if you had broken down the issue briefly at the start then went in depth into the solutions. This would saved me from watching the full video. I understand you want people to watch it but I'm already a seasoned developer.
@avi7278
@avi7278 Жыл бұрын
"way better" or "so much better" but not "way much better"
@SachalChandio
@SachalChandio Жыл бұрын
nice
@matheuslopes7956
@matheuslopes7956 Жыл бұрын
First comment!! Thank's
@dq303
@dq303 Жыл бұрын
Promise.all is slow if working with larger data set , don’t like it
@Kaviarasu_NS
@Kaviarasu_NS Жыл бұрын
❤🖖
@sp3cterproductions
@sp3cterproductions Жыл бұрын
Nice video. One thing to note, this is not parallel execution, parallel execution refers to multi-threading. This is concurrency because JS is inherently single-threaded. Technically you can have multiple threads with JS but this would require the help of workers.
@akifimran9780
@akifimran9780 Жыл бұрын
Unnecessarily long vid. But good tip thanks.
@rishabhgusai96
@rishabhgusai96 Жыл бұрын
This comment will throw me out of the window. Use Observables instead and zip it.
@amitei1183
@amitei1183 Жыл бұрын
Okay, I just wasted a few minutes of my life on a video that moves two awaits to Promise.all for no particular reason. As other wise men already said, the video is a bit misleading and the solution you provide is not the best because you are still waiting for ALL the promises to be resolved and then applying them to UI. If requests are separate, do not depend on each other, and can be executed in parallel (as shown in your example), just put them in separate useEffects and that's it. The order does not matter, whenever the query is completed, its results will be displayed in the UI. There is no need to complicate such a simple thing. Moreover, this approach is easier to understand, because in the context of one request, you are not interested in the other (they are independent, remember?). And if there is a need to change or refactor something, it will be much easier. For example, you could use a different set of dependencies to refetch, or just copy one request and paste it somewhere else.
@jasper2virtual
@jasper2virtual Жыл бұрын
I agree with you, afaik js runtime is single threaded . Promise all doesn't make anything faster. It just make code more unreadable.
@haydenbush3545
@haydenbush3545 Жыл бұрын
Exactly it looks like the products request was much slower than the category request, why are we waiting to render the categories? I typically just have the one primary useEffect and set the states in the Promise(...).then()
@bryanrobert2274
@bryanrobert2274 Жыл бұрын
I'm kinda new in JS programming, so I may say very stupid things but Do we agree that in fetchData2, there is a problem ? He fetch Categories and TopCategory, then fetch ProductsByCategory So if Categories takes 10 sec and TopCategory 1sec, ProductsBycategory won't run before 10sec, while it only depends on TopCategory The newby in me whould have write something like : fetchCategories().then((d) => setCategories(d)) fetchTopcategory().then((d) => fetchProductsByCategory(d.name).then((d2) => setProducts(d2))) //I would probably create a new func for the inner fetch for clarity purposes
@be2wa
@be2wa Жыл бұрын
YOU are using Promises the wrong way.
@gearmeout
@gearmeout Жыл бұрын
No I’m not, the title is a lie.
@korkut31
@korkut31 10 ай бұрын
how funny english it is. so funny
@hikari1690
@hikari1690 Жыл бұрын
I don't really like promise.all cause if an error happens then you'll spend hours figuring out why. Sides, the title shouldn't be so clickbaity and mention multiple or something. But you do you. Oh and do please clear your sinuses... It makes you sound so whiny
@1879heikkisorsa
@1879heikkisorsa Жыл бұрын
This video is misleading and shows some weknesses. I think the creater should care more about neat solutions before posting videos about it. For example in the "fetchData2" there's no reason why you want the categories to be awaited first, if you do not even care about them for later use. Just imagine if these categories take a long time, but the topCategories not, then you're wasting a lot of time for nothing. Since this is not the first mistake I will be avoiding this channel in the future.
@vamshikrishnareddy76
@vamshikrishnareddy76 Жыл бұрын
i tried doing this ````const [dataone, setdataone] = useState([]); const [datatwo, setdatatwo] = useState([]); const fetchMovies = async () => { const response = await Promise.all([ axios.get("url"), axios.get("url"), ]); console.log(response) setdataone(response[0]) setdatatwo(response[0]) conosole.log(dataone) }, useEffect(() => { fetchMovies(); }, []);``` console.log(dataone) is logging an empty array but console.log(response) logs out the data can some one help
Rust is the Perfect language For You
13:13
CoderOne
Рет қаралды 64 М.
UI Libraries Are Dying, Here's Why
13:28
Theo - t3․gg
Рет қаралды 252 М.
Surprise Gifts #couplegoals
00:21
Jay & Sharon
Рет қаралды 26 МЛН
Glow Stick Secret 😱 #shorts
00:37
Mr DegrEE
Рет қаралды 19 МЛН
Callbacks, Promises, Async Await | JavaScript Fetch API Explained
1:05:05
Responsive CSS Will Never Be The Same
12:08
Web Dev Simplified
Рет қаралды 263 М.
Beginner React.js Coding Interview (ft. Clément Mihailescu)
36:31
Ben Awad
Рет қаралды 2,1 МЛН
The Magical React Hook That Makes your Components Smaller
11:30
16.11: Promises Part 1 - Topics of JavaScript/ES6
24:53
The Coding Train
Рет қаралды 331 М.
#22 - Promise Chaining in JavaScript
12:29
Naveen AutomationLabs
Рет қаралды 2,7 М.
Async JavaScript - Callbacks, Promises, Async/Await
25:10
codeSTACKr
Рет қаралды 63 М.
Why I Moved from React Redux to Zustand and Why You Should Too!
19:24