You're using Javascript Promises The wrong way

SdĂ­let
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

Komentáƙe • 82

  • @joelm2858
    @joelm2858 Pƙed rokem +173

    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 Pƙed rokem +6

      MVP guy

    • @yaroslavqwerty8609
      @yaroslavqwerty8609 Pƙed rokem

      Agree, and what if there is an error in request, will array destructuring work?

    • @joelm2858
      @joelm2858 Pƙed rokem +12

      @@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 Pƙed rokem +25

      .allSettled anyone? nope? ok

    • @ibnShafee
      @ibnShafee Pƙed rokem

      Yes, I was thinking the same

  • @faythe03
    @faythe03 Pƙed rokem

    That's very insightful, for when the data between the promises is not always dependant

  • @huncho6295
    @huncho6295 Pƙed rokem

    Thanks for sharing your experience on handling async fetching

  • @BogacGuven
    @BogacGuven Pƙed rokem +5

    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.

  • @ukaszzbrozek6470
    @ukaszzbrozek6470 Pƙed rokem +78

    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 Pƙed rokem

      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 Pƙed rokem

      @@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.

  • @MF-hx8or
    @MF-hx8or Pƙed rokem +1

    It was wonderful, thank you 😍😍😍

  • @MrShaheer
    @MrShaheer Pƙed rokem +1

    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.

  • @ayoub.k
    @ayoub.k Pƙed rokem +65

    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 Pƙed rokem

      Could you explain when it is bad to use this approach

    • @ayoub.k
      @ayoub.k Pƙed rokem +4

      @@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 Pƙed rokem +4

      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 Pƙed rokem +2

      @@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 Pƙed rokem

      @@ayoub.k He clearly stated it.

  • @rajaj6043
    @rajaj6043 Pƙed rokem

    Thanks for sharing, Nice tips!!!

  • @shivangm24
    @shivangm24 Pƙed rokem

    Got to learn new way to optimize for parallel use cases. Tanks!!

  • @harrisonekpobimi4764
    @harrisonekpobimi4764 Pƙed rokem

    Insightful. Thanks

  • @focusiam2027
    @focusiam2027 Pƙed rokem

    Hello, thank you for this tutorial. Do you have the video where you build this app?

  • @K.Huynh.
    @K.Huynh. Pƙed rokem

    thank for sharing!

  • @lamargtv2572
    @lamargtv2572 Pƙed rokem

    Amazing!

  • @eony
    @eony Pƙed rokem

    that's pretty cool, thanks.

  • @ThiagoLucioBittencourt
    @ThiagoLucioBittencourt Pƙed rokem

    Amazing examples. Open knowledge about. Thanks to share.this

  • @jorgericaldi6438
    @jorgericaldi6438 Pƙed rokem

    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) ?

  • @irfanmohammad7269
    @irfanmohammad7269 Pƙed rokem +1

    Nice content

  • @noriller
    @noriller Pƙed rokem

    Last case, if possible, would try to have a backend API doing that.

  • @yadneshkhode3091
    @yadneshkhode3091 Pƙed rokem

    thanks man

  • @utkukemalcifci9525
    @utkukemalcifci9525 Pƙed rokem

    Thanks :)

  • @sinapiranix
    @sinapiranix Pƙed rokem

    best video👌👌

  • @esequielalbornoz5271
    @esequielalbornoz5271 Pƙed rokem +7

    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 Pƙed rokem +2

      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 Pƙed rokem +1

      ​@@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".

  • @humansaremortal3803
    @humansaremortal3803 Pƙed rokem

    How do I setup "loading" with this way of coding?

  • @osquigene
    @osquigene Pƙed rokem

    That's literally the first thing you would learn about asynchronous programming so I doubt people would not know about this.

  • @SuperNZY
    @SuperNZY Pƙed rokem

    GJ!

  • @matheuslopes7956
    @matheuslopes7956 Pƙed rokem

    First comment!! Thank's

  • @sogggy
    @sogggy Pƙed rokem

    Noice!

  • @Lindaine
    @Lindaine Pƙed rokem

    Isn't this concurrency instead of parallel?

  • @AngusMcIntyre
    @AngusMcIntyre Pƙed rokem

    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"

  • @SachalChandio
    @SachalChandio Pƙed rokem

    nice

  • @yolopolo5783
    @yolopolo5783 Pƙed rokem

    Can't we just create two seperate async functions

  • @popuguytheparrot_
    @popuguytheparrot_ Pƙed rokem

    Sooo, what about promises?

  • @caiyuhui
    @caiyuhui Pƙed rokem +1

    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) .

  • @orielsy
    @orielsy Pƙed rokem

    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.

  • @Kaviarasu_NS
    @Kaviarasu_NS Pƙed rokem

    â€đŸ––

  • @letri8757
    @letri8757 Pƙed rokem +8

    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 Pƙed rokem

      You didn't watch the entire video

    • @letri8757
      @letri8757 Pƙed rokem

      ​@@EhteshamShahzad yup i didn't because this is not the wrong way :).

    • @EhteshamShahzad
      @EhteshamShahzad Pƙed rokem

      ​@@letri8757 you should. and then revisit your comment

    • @letri8757
      @letri8757 Pƙed rokem

      @@EhteshamShahzad sorry nope :)

    • @EhteshamShahzad
      @EhteshamShahzad Pƙed rokem

      @@letri8757 you must be a fun colleague to work with :)

  • @akifimran9780
    @akifimran9780 Pƙed rokem

    Unnecessarily long vid. But good tip thanks.

  • @creayt
    @creayt Pƙed rokem

    This video took 10 minutes to explain a 30 second concept, well done

  • @avi7278
    @avi7278 Pƙed rokem

    "way better" or "so much better" but not "way much better"

  • @sp3cterproductions
    @sp3cterproductions Pƙed rokem

    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.

  • @dq303
    @dq303 Pƙed rokem +1

    Promise.all is slow if working with larger data set , don’t like it

  • @be2wa
    @be2wa Pƙed rokem

    YOU are using Promises the wrong way.

  • @rishabhgusai96
    @rishabhgusai96 Pƙed rokem +1

    This comment will throw me out of the window.
    Use Observables instead and zip it.

  • @korkut31
    @korkut31 Pƙed 11 měsĂ­ci

    how funny english it is. so funny

  • @amitei1183
    @amitei1183 Pƙed rokem +4

    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 Pƙed rokem

      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 Pƙed rokem

      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 Pƙed rokem

      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

  • @gearmeout
    @gearmeout Pƙed rokem

    No I’m not, the title is a lie.

  • @hikari1690
    @hikari1690 Pƙed rokem

    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 Pƙed rokem

    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 Pƙed rokem

    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