You're using Javascript Promises The wrong way
VloĆŸit
- Äas pĆidĂĄn 5. 11. 2022
- đ§ 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
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()])`
MVP guy
Agree, and what if there is an error in request, will array destructuring work?
@@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
.allSettled anyone? nope? ok
Yes, I was thinking the same
That's very insightful, for when the data between the promises is not always dependant
Thanks for sharing your experience on handling async fetching
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.
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.
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.
@@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.
It was wonderful, thank you đđđ
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.
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.
Could you explain when it is bad to use this approach
@@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.
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
@@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
@@ayoub.k He clearly stated it.
Thanks for sharing, Nice tips!!!
Got to learn new way to optimize for parallel use cases. Tanks!!
Insightful. Thanks
Hello, thank you for this tutorial. Do you have the video where you build this app?
thank for sharing!
Amazing!
that's pretty cool, thanks.
Amazing examples. Open knowledge about. Thanks to share.this
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) ?
Nice content
Last case, if possible, would try to have a backend API doing that.
thanks man
Thanks :)
best videođđ
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
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))
â@@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".
How do I setup "loading" with this way of coding?
That's literally the first thing you would learn about asynchronous programming so I doubt people would not know about this.
GJ!
First comment!! Thank's
Noice!
Isn't this concurrency instead of parallel?
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"
nice
Can't we just create two seperate async functions
Sooo, what about promises?
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) .
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.
â€đ
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).
You didn't watch the entire video
â@@EhteshamShahzad yup i didn't because this is not the wrong way :).
â@@letri8757 you should. and then revisit your comment
@@EhteshamShahzad sorry nope :)
@@letri8757 you must be a fun colleague to work with :)
Unnecessarily long vid. But good tip thanks.
This video took 10 minutes to explain a 30 second concept, well done
"way better" or "so much better" but not "way much better"
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.
Promise.all is slow if working with larger data set , donât like it
YOU are using Promises the wrong way.
This comment will throw me out of the window.
Use Observables instead and zip it.
how funny english it is. so funny
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.
I agree with you,
afaik js runtime is single threaded . Promise all doesn't make anything faster. It just make code more unreadable.
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()
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
No Iâm not, the title is a lie.
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
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.
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