Tips For Using Async/Await in JavaScript

แชร์
ฝัง
  • เผยแพร่เมื่อ 8 ก.ค. 2024
  • Async/Await is a much cleaner syntax for working with promises than using .then(). Let's take a look at how to convert an asynchronous function from using .then() to using async/await and learn a few tips along the way.
    00:00 - Intro
    00:45 - Fetch Example with .then
    01:30 - Convert Promises to Async/Await
    04:40 - Use Try/Catch for Errors
    06:30 - Async Functions Return a Promise
    07:40 - Use IIfe for Top-Level Await
    09:00 - Promise.all()
    _____________________________________________
    Newsletter 🗞
    Interested in exclusive content and discounts? 🤯 Sign up for the newsletter!
    www.jamesqquick.com
    _____________________________________________
    Connect with me 😀
    Live streams on Twitch - / jamesqquick
    Follow me on Twitter - / jamesqquick
    Join the 💬 Discord Server 💬 - / discord
    _____________________________________________
    COURSES 💻
    Learn how to build Fullstack apps with React and Serverless Functions - www.jamesqquick.com/courses/r...
    Learn everything you need to know about Visual Studio Code - www.udemy.com/learn-visual-st...
    Build a Quiz App - www.udemy.com/build-a-quiz-ap...

ความคิดเห็น • 459

  • @TheNelsonc24
    @TheNelsonc24 3 ปีที่แล้ว +15

    You just don't give a basic example of the usage of asyc/await, you give how to use them in multiple calls scenarios. Great work!!! And thank you for sharing!

  • @QmFhbFpldnV2
    @QmFhbFpldnV2 2 ปีที่แล้ว +14

    I finally got the idea of async in JS, up to this moment I struggled with understanding sequences of actions when running async code. Now I understand it completely, thanks James!

  • @nikkittb
    @nikkittb 3 ปีที่แล้ว +13

    This has been a big help James, thanks so much! I have been struggling trying to convert promises to async/await functions and seeing you walk us through it step-by-step really helped a lot!

  • @danielwisniewski5989
    @danielwisniewski5989 2 ปีที่แล้ว +4

    Heeey! Thanks for all that async/await content on Your channel! I did get my first junior react dev job thanks to You! I used async/await and try-catch in my tech meeting interview task, and they were impressed! I'm really, really grateful for that!

  • @varshasingh1299
    @varshasingh1299 3 ปีที่แล้ว +2

    Wow!! I was literally waiting for this content...very nicely explained❤️ thanks James..

  • @TheDandef
    @TheDandef 2 ปีที่แล้ว +69

    I must say I still think working with Promises is a lot more clean than working with async/await. With async/await, you end up with a lot more LOC's, you still have to deal with a promise if values are returned from the async function, or you have to use top-level async/await, which is ultimately undesirable since asynchronous code can lead to frustrating long debugging when not applied correctly in respect to synchronous code.

  • @jedirvine
    @jedirvine 3 ปีที่แล้ว

    Clearest explanation I've found for how these all relate. Thanks!

  • @ignacioanezin2352
    @ignacioanezin2352 3 ปีที่แล้ว

    Loved this one! Thanks for clearing it out for me. Keep it up!! 🚀🎉

  • @ricdotnet
    @ricdotnet 3 ปีที่แล้ว +1

    this is one of the most useful videos I have watched in a long time. Thanks man 👍

  • @rexxon1611
    @rexxon1611 2 ปีที่แล้ว +1

    The best video that explains the two different ways of calling async function! await is always much cleaner than the .then .catch.

  • @jonathanroy72
    @jonathanroy72 3 ปีที่แล้ว +32

    I'm glad there a lot of people disagreeing with you. Your video is nice and well explained, but I got to say I prefer ".then" over "async/await". I simply found it way easier to understand. It's closer to how a human would think about something asynchronous. "do this and when you will have the data, then do that." when I was learning JavaScript, the async/await was bugging me and what made me understand it was the "then"

    • @RyanFlores9
      @RyanFlores9 2 ปีที่แล้ว +1

      I agree. Seems like a lot of (relatively) newer JavaScript improvements are making it possible to write more lean and compact code, but that doesn't necessarily make it more (human) readable. One could argue it could be due to lack of familiarity, but for me personally, I'd use that argument for learning a new framework/toolkit/API/SDK over an evolving language. I see other languages improving over time, but a lot of changes that were made to JavaScript introduced a lot of inconsistencies IMHO. The changes introduced a lot more "ways to skin a cat" instead of focusing on readability and a single "best/right way" to do things.

    • @PerttuSaarsalmi
      @PerttuSaarsalmi 2 ปีที่แล้ว +2

      I disagree! I can’t wait to get refactoring our messy asynchronous code in my current project! 😂

    • @arturmrozinski7536
      @arturmrozinski7536 2 ปีที่แล้ว +3

      I have a 300 lines long test and async/await cut execution time from 14 sec to 4. Who cares about human undertanding? Its not for regular bread buyer. You learn it in a day and benefit for life. '.then' is slowwww

    • @chess4964
      @chess4964 2 ปีที่แล้ว +3

      .then is just for old people, you need to cope up 😂

    • @thepetesmith
      @thepetesmith ปีที่แล้ว

      Jonathan, you’ll get used to it. It’s cleaner.

  • @xpo11ox
    @xpo11ox 3 ปีที่แล้ว +3

    I finally learned how to use the Promise.all method in an Async/Await function. Thanks, bro for your work...

    • @JamesQQuick
      @JamesQQuick  3 ปีที่แล้ว +1

      You’re very welcome!!

  • @sordahl
    @sordahl 2 ปีที่แล้ว

    James, you are a legend :) have seen multiple of your videos and your approach to coding is very inspiring.

  • @stevenleonmusic
    @stevenleonmusic 3 ปีที่แล้ว +66

    " *We* completely missed that"-Hey man you're flying solo on this one.

    • @JamesQQuick
      @JamesQQuick  3 ปีที่แล้ว +5

      What? lol

    • @BobbyBundlez
      @BobbyBundlez 2 ปีที่แล้ว

      The haters on these comments is just so funny. Shut up bro this tutorial is great

    • @stevenleonmusic
      @stevenleonmusic 2 ปีที่แล้ว

      @@BobbyBundlez I'm pretty sure I was just poking fun at his use of "we" when the video is just him, alone. It's a 20-minute video from a year ago though so it's not really worth my time to try and remember. I cannot imagine why it was worth your time commenting to begin with.

    • @zeta519
      @zeta519 2 ปีที่แล้ว +1

      @@stevenleonmusic says the person who replied with an entire essay

    • @stevenleonmusic
      @stevenleonmusic 2 ปีที่แล้ว

      @@zeta519 Buddy if you think that's an essay all I can say is you need to read more.

  • @ChrisLove
    @ChrisLove 2 ปีที่แล้ว

    Great tutorial!
    You have a great, even keel persona in your presentation and that works great!
    I have personal OCD sort of things around try catch I am trying to overcome. You made this much more approachable :)
    Love the use of the .map call to manage the results!!! Great little trick.

  • @stevenng1040
    @stevenng1040 ปีที่แล้ว

    One of the clearest explanation of async/await I have ever seen. Thanks James!!

  • @RobertoGPuentesDiaz
    @RobertoGPuentesDiaz 3 ปีที่แล้ว

    Congratulations
    Finally. A good path to understand. Tks man.

  • @LogansRun45
    @LogansRun45 3 ปีที่แล้ว

    Thank you for this video. Really helped me understand not only why but how to migrate from .then to await. As a bonus, you helped me solve the multiple url problem I was going to work on this weekend! Thanks again.

    • @JamesQQuick
      @JamesQQuick  3 ปีที่แล้ว

      Glad it was helpful!

  • @JamesQQuick
    @JamesQQuick  3 ปีที่แล้ว +1

    Hey all! I have a few clarifications about Promise.all coming in a new video shortly.

    • @adamlbarrett
      @adamlbarrett 3 ปีที่แล้ว

      It’s nice that you made the video, but actually you weren’t wrong then and now the “I was wrong”’ video has misinformation about Promise.all()
      You do the best with what you have at the time though, I love that you wanted to do the right thing and admit you were wrong …unfortunately you were not.
      The single threaded nature if JavaScript the language allows it to be predictable but you can call out to host systems and do things in parallel, like for example making request.
      Simple proof would be just making a quick service that responds after 1 second and you’ll see that the Promise.all() version does in fact take about 1 second while awaiting each takes approx 3.
      The stuff that does not happen in parallel is placing resolutions in the micro task and dealing with the stack calls as the event loop resolved them but that is trivial compared to the network call.
      Anyway, nice to try and do the right thing, can’t wait for the I was wrong about being wrong video 🙂

    • @JamesQQuick
      @JamesQQuick  3 ปีที่แล้ว

      @@adamlbarrett Yep, I'm now scrambling to figure out how to fix this again lol I started overthinking it all while reading comments. I'm creating another video shortly for extra clarification and unlisting the other :)

    • @adamlbarrett
      @adamlbarrett 3 ปีที่แล้ว

      @@JamesQQuick I immediately regretted adding to the cesspool that is "TH-cam comments" as soon as I posted it. But good luck with this whole thing!

    • @adamlbarrett
      @adamlbarrett 3 ปีที่แล้ว

      @@JamesQQuick You may want to dip into parallel vs concurrent when you explain why the Promise.all() happens at the same time.
      People get pedantic about the word parallel sometimes, and I think that was the cause of the original commenters confusion

    • @JamesQQuick
      @JamesQQuick  3 ปีที่แล้ว

      @@adamlbarrett Uploading a new video shortly and mention a bit of the difference there!

  • @InsaneMetalSoldier
    @InsaneMetalSoldier 2 ปีที่แล้ว

    I can finaly say I understand all this promises and async stuff. This video was perfect to wrap it all.

  • @gregclarkreasons
    @gregclarkreasons 3 ปีที่แล้ว

    Thank you for this awesome explanation and demonstration!

  • @rafaelcanchola9417
    @rafaelcanchola9417 3 ปีที่แล้ว +3

    Amazing, just about a few hours I was making several sequential fetch's to an API, and now I crossed with your video, now I feel the power, and how to make then kinda asynchronous again, thanks.

  • @nemesioansorin
    @nemesioansorin 2 ปีที่แล้ว +1

    ..., just one of your best episodes - many JS programmers are doing `this` or `that` just because one API set of paradigms or another will give them what they need for their immediate task. But the deep knowledge reside in knowing WHY `this` is better `that` in very a particular or a very general circumstance. It would be perfect if you can talk more about how JS engine is working behind the scene, about JS Event Loop / JS Call Stack / etc. Thanks again for your very explicit shows.

  • @johnkeck
    @johnkeck 2 ปีที่แล้ว

    Very clear explanation! Thank you so much!

  • @rameshjp7045
    @rameshjp7045 3 ปีที่แล้ว

    Thanks a lot for sharing this! This really helped.

  • @rolandodiaz3381
    @rolandodiaz3381 2 ปีที่แล้ว

    Thank you!!! i was stuck with this for 2 days but now I was able to solve the problem.
    Amazing tutorial.

  • @akusa03
    @akusa03 3 ปีที่แล้ว +2

    Thanks for the wonderful video. All concepts cleared. I was using multiple awaits without understanding the reason behind. The promise.All solution is fantastic. Waiting for more such tutorial.

    • @JamesQQuick
      @JamesQQuick  3 ปีที่แล้ว +1

      So glad this was helpful!! :)

  • @dgonch
    @dgonch 3 ปีที่แล้ว

    Great as always, thank you.

  • @seismicoz
    @seismicoz 3 ปีที่แล้ว +5

    I think this cannel is the most useful one about programming, especially for JS. Thank you!

  • @DuncanMargetts
    @DuncanMargetts 3 ปีที่แล้ว

    Awesome! Thanks, learnt heaps.

  • @AdamCole1
    @AdamCole1 ปีที่แล้ว

    Really well explained. Thank you.

  • @sabuein
    @sabuein ปีที่แล้ว

    Thank you, James.

  • @184Simon
    @184Simon 2 ปีที่แล้ว

    Perfect explanation!

  • @TheVisionBT
    @TheVisionBT 2 ปีที่แล้ว

    great tuto ! thank you!

  • @matthiaskolley1048
    @matthiaskolley1048 3 ปีที่แล้ว +35

    fetch(url).then(res=>res.json()).then(console.log).catch(console.error);
    Anyway: what about `finally`?

    • @MrMudbill
      @MrMudbill 3 ปีที่แล้ว +2

      Finally works as expected for both approaches. Either with chaining .finally() after .catch()/.then() or in an async/await "finally" block on the try-catch

  • @oneinazillion
    @oneinazillion 2 ปีที่แล้ว +8

    One other thing to probably be weary of, if you have too many await statements or long chained promises and then succeed them by some logic that is not directly related to the response they generate, you would potentially block JS from rendering the UI. Its important to put all your awaits only within an async function scope and not do anything else in there.

    • @JoseMiguelLoor
      @JoseMiguelLoor 2 ปีที่แล้ว

      I think that a good example of that is using observables in typescript

  • @juliusekandem
    @juliusekandem 2 ปีที่แล้ว

    Thank you soooo much!!! this really helped.

  • @CvetaMobi
    @CvetaMobi ปีที่แล้ว

    Thank you!!!! Very understandable!

  • @ewalshp
    @ewalshp 2 ปีที่แล้ว

    Thnak you. Excellent video.

  • @PieJee1
    @PieJee1 2 ปีที่แล้ว +1

    Await/async has two very great advantages. If you dont transpile to es5 async functions give better stacktraces. Also error handling is easier to read as many programmers make mistakes about what is the difference between catch and the second optional argument to then

  • @PrimephotoStudio
    @PrimephotoStudio 3 ปีที่แล้ว

    Thank you for sharing this with us very helpful.

  • @cli23
    @cli23 3 ปีที่แล้ว

    Great explanation!

  • @mareboinaravi5272
    @mareboinaravi5272 3 ปีที่แล้ว

    Useful content,200th Like ❤️

  • @sak1b
    @sak1b 3 ปีที่แล้ว

    Man it's going to make my life easier, thank you.

  • @nicholascutlip
    @nicholascutlip ปีที่แล้ว

    Thanks! I'm new to JS and building the back end of a web app. This is exactly the info I was looking for.

  • @Hertog_von_Berkshire
    @Hertog_von_Berkshire 2 ปีที่แล้ว +31

    async/await being syntactically "cleaner" is pretty well a value judgement. There are some real advantages to async/await though, chiefly (1) an asyncFunction is guaranteed to throw by way of returning a rejected promise (or rejecting its returned promise), even from a sync code fail ... the advantage accrues in the caller (2) .then().then() related scope issues disappear ... remember all those "how do I access previous results?" questions in StackOverflow?

    • @timderks5960
      @timderks5960 2 ปีที่แล้ว +3

      I definitely agree on the "cleaner" part, the example from this video is a lot cleaner in the .then syntax IMO. It can also be a lot shorter than the async await version, since it could easily be on 4 lines without losing any clarity. Even though the async await version is a lot more verbose, it's a lot messier than the .then version.

    • @thatguynamedmorgoth8951
      @thatguynamedmorgoth8951 2 ปีที่แล้ว +3

      Honestly, the promise.all example was really ugly.
      I'd rather just do:
      let urls=[....... ]
      return Promise.all(
      urls.map(
      url => fetch(url).then(res=>res.json())
      )
      )
      This is so much cleaner than the example in the vid

    • @mlntdrv
      @mlntdrv 2 ปีที่แล้ว

      @@thatguynamedmorgoth8951 Promise/then hell detected - the then is nested. Should be chained under the Promise.all() call.

    • @thatguynamedmorgoth8951
      @thatguynamedmorgoth8951 2 ปีที่แล้ว

      @@mlntdrv the then callback would also need to have a map operation which I find kinda ugly, though it's a valid answer

  • @mudyeet_
    @mudyeet_ 3 ปีที่แล้ว +1

    even though I've been using this stuff for a good while now, the Promise.all part was really useful :D

  • @johnrodger5467
    @johnrodger5467 2 ปีที่แล้ว +1

    They both have their place. Promises are cleaner for pipeline type stuff, particularly if you can go point-free:
    fetch(url)
    .then(res => res.json())
    .then(console.log)
    .then(console.error)
    It's often a more concise syntax, (reduce lines of code by 30%) so can be great for testing also. Also less cognitive load.
    Async await has its place, especially for writing big chunks of procedural code where you really need space to work in. Also it's easier to debug.

    • @DemanaJaire
      @DemanaJaire 2 ปีที่แล้ว

      Very much that, babs.

  • @elisasoto1
    @elisasoto1 3 ปีที่แล้ว

    Great explanation. Cristal clear

  • @maxtate906
    @maxtate906 2 ปีที่แล้ว

    super awesome tutorial!!!
    i learned async/await in first 5 minutes of video.best video.❤❤❤❤❤❤❤❤
    much love from iran

  • @MatheusSouzaRigote
    @MatheusSouzaRigote 3 ปีที่แล้ว +1

    Muito bom, parabéns. Sempre achei um problema utilizar Async/Await

  • @SaidElnaffar
    @SaidElnaffar 2 ปีที่แล้ว

    Wow -- a tough topic and you managed to explain it with good examples.

  • @Asli_
    @Asli_ 2 ปีที่แล้ว

    Thanks this helped , especially the Promise.all() part.

  • @cmtv357
    @cmtv357 2 ปีที่แล้ว

    This helped a lot. Thanks ma!

  • @smithscarborough
    @smithscarborough 3 ปีที่แล้ว

    Super helpful video. Thank you!

    • @JamesQQuick
      @JamesQQuick  3 ปีที่แล้ว +1

      Glad it was helpful!

  • @PFOctavio
    @PFOctavio 2 ปีที่แล้ว

    Great material, thank you very much!!!!!!!!!!!!!!!!!!!!!!

  • @yoonustehraniam8891
    @yoonustehraniam8891 2 ปีที่แล้ว

    Useful advice 👍

  • @555pontifex
    @555pontifex 2 ปีที่แล้ว

    Is it possible to chain the methods with async await, as in "const data = await fetch(url).json();" ???

  • @SebastianStein85
    @SebastianStein85 2 ปีที่แล้ว

    Thx, helped me a lot to improve some ugly parts in a current project. Specially the part with Promise.all.

  • @hurleywflow2227
    @hurleywflow2227 3 ปีที่แล้ว

    Love that !

  • @atiqbaqi
    @atiqbaqi 2 ปีที่แล้ว

    very helpful video, easy to understand

  • @Pareshbpatel
    @Pareshbpatel 2 ปีที่แล้ว

    Thanks, James

  • @ampinkus
    @ampinkus ปีที่แล้ว

    Hi James, many thanks for the clear explanation!
    I have a question: What code do I need to add in order to load on an array the information that I get on “data” instead of printing it to the console?
    Let’s say I have an array: answerList: any = [ ];
    And I want to load all the Jason / Jason’s that I get from the WEB site.
    Many thanks in advance and best regards,

  • @Kunal-jp8tn
    @Kunal-jp8tn 2 ปีที่แล้ว

    amazing tutorial thanks.

  • @michaelvadney5803
    @michaelvadney5803 2 ปีที่แล้ว +1

    Very neat.
    Dumb question: what is this tool that you are using for editing and viewing results?
    Thanks!

  • @contentshark5122
    @contentshark5122 2 ปีที่แล้ว

    lovely !!

  • @pratyushkumar5740
    @pratyushkumar5740 2 ปีที่แล้ว

    Nice work♥️

  • @koltuz
    @koltuz 2 ปีที่แล้ว +2

    7:10 wait, how do i get the data in a variable if what i want is to use that and not print the results in console

  • @Abdallah_Ismail
    @Abdallah_Ismail 10 หลายเดือนก่อน

    At 13:22 could we ude reduce instead of map?
    will it also work?

  • @BrendanMetcalfe
    @BrendanMetcalfe 3 ปีที่แล้ว

    Nice video!

  • @vladometodiev3086
    @vladometodiev3086 ปีที่แล้ว

    Thanks dude!

  • @jeromedicharry1340
    @jeromedicharry1340 3 ปีที่แล้ว +2

    Thanks for sharing ! Will try to apply this to my current react project where i am fetching companies then convert all their adresses to lat, lng with the google geocoding api and then display a google map with all the markers. Would be a nice video ^^

  • @kr3xy140
    @kr3xy140 2 ปีที่แล้ว

    At 15:22, should we also await result.json() or is it unnecessary?

  • @sumitpandey7446
    @sumitpandey7446 2 ปีที่แล้ว

    Well sumed up mate

  • @PetarVasilevX
    @PetarVasilevX 2 ปีที่แล้ว

    Is it possible, lets say that fetch1 takes 1 second and fetch2 and fetch3 take 2 seconds, to do the .json() promise as soon as fetch1 returns its results instead of waiting for all 3 fetch to return?

  • @m2kdevelopments
    @m2kdevelopments 3 ปีที่แล้ว

    Awesome Video

  • @nicknesler
    @nicknesler 2 ปีที่แล้ว

    Watching someone make a coding error on TH-cam is the adult version of Steve asking where Blue is. He's right there! We can see his tail! You forgot await!

  • @paoro814
    @paoro814 2 ปีที่แล้ว

    thank you man.

  • @jazper808
    @jazper808 2 ปีที่แล้ว

    I wanna marry your code it looks so clean :)

  • @alexhe8276
    @alexhe8276 2 ปีที่แล้ว

    Thanks a lot James, this is reall helpful. I do have a quetion that if I have a function A() using async/await, when I call A() in another function B(), do I still need use "await A();" or just "A()" should do the work?

  • @devprakash5320
    @devprakash5320 2 ปีที่แล้ว

    loved it

  • @yb3985
    @yb3985 2 ปีที่แล้ว

    So, my mindset all this time is wrong. I thought you still have to use then catch with await keyword. Now, i'm fully understand, thank you for this lesson.

  • @SinisterSlay1
    @SinisterSlay1 2 ปีที่แล้ว

    change your fetch(url1 // etc) to fetch(url1).then(r=>r.json()) and you remove the need for the array map entirely. You can also add .catch to each to handle errors specific to each URL. Just an example of the power of combining await and promises together to make clean code. This trick becomes useful when you end up needing several different resources at the same time (instead of 3 todo's as shown here that return the exact same structure). Invariable some years later one of those calls will change and you will end up using another .then to reformat the data to match whatever it needs to be.

  • @MagnusAnand
    @MagnusAnand 3 ปีที่แล้ว

    Great video

  • @victory_lucky
    @victory_lucky 3 ปีที่แล้ว +1

    I'm currently working on a project where I needed to upload images to an API and get the returned URL so I could store it in the database, and this video helped in solving the puzzle.

  • @tapantorbangla
    @tapantorbangla 3 ปีที่แล้ว

    nicely explained.. just gone fear about async, await.. thanks a lot.

  • @AlThePal78
    @AlThePal78 3 ปีที่แล้ว

    thank you for explaining properly how getting that data needs to be handled by a .then. I tried understanding stack overflow but they just rude lol

  • @raguilaru
    @raguilaru 3 ปีที่แล้ว

    Really great video! Many good insights on how promises work. I agree async/await > .then

    • @RyanFlores9
      @RyanFlores9 2 ปีที่แล้ว +1

      Maybe in some scenarios, but not all.

  • @RyanFlores9
    @RyanFlores9 2 ปีที่แล้ว +2

    Excellent video. You explained things very clearly and coherently. I wish I had your skill to explains things the way you did in this video. This goes without saying that I'm not 100% convinced that I should refactor all my code to use await/async. But I'm glad to see that I have the option and ability to use them. Thanks.

    • @JamesQQuick
      @JamesQQuick  2 ปีที่แล้ว

      Glad this was helpful. It's definitely good to be aware of your options1

  • @stainlesssteellemming3885
    @stainlesssteellemming3885 2 ปีที่แล้ว +5

    I may be overcomplicating a simple example here, and really appreciate the video, but I'm trying to move to JS (actually tyoescript) from hard-real-time embedded C. I'm wondering why you would bother with the final "await".
    The last line of your function is effectively "return (await promise.all(...));". So, you wait here for all the promises to resolve and then return the data. But an async function always returns a promise, which means it has to be called as either "await foo" or "foo.then()".
    In which case, why not simply "return promise.all(...)" and let the caller decide when they want to do the final synchronous wait? Is this a best practice idiom or is there something fundamental I'm missing?

    • @JamesQQuick
      @JamesQQuick  2 ปีที่แล้ว

      You’re spot on you could definitely do that! Just an oversight on my end

    • @ominousri
      @ominousri 2 ปีที่แล้ว

      I think I'm seeing an overcomplication from a simple example as well. Finding async/await can create lots of spaghetti in the wrong hands. It returns promises either way so there's no escaping then(). Then catch() is merely replaced with a try{}catch{} here. 6 and 1/2 dozen of the other? And arguments support await so inside your LoadData() I can just invoke a topLevelFunction(await res.json()); which topLevelFunction has no async/await awareness on. There's a million ways to skin a cat these days and it can be far too much nuance, which you did preface this with.

  • @roziscoding
    @roziscoding 3 ปีที่แล้ว +83

    The problem with this is that you create a lot of intermediary variables that you're not really gonna use just so you don't have `. then` calls. You could've chained `then`s until you got the data and then awaited on that to get the data on a variable.
    Async / await isn't meant to eliminate then calls, it's meant to simplify working with them

    • @joshparker5779
      @joshparker5779 3 ปีที่แล้ว +5

      Good point. I want to mention something else to consider. Having a lot of local variables can be convenient if you're using a debugger because the debugger would show all the values at a glance when it hits a breakpoint in scope. It's not always necessary, of course, but it can be nice sometimes.

    • @akashchoudhary8162
      @akashchoudhary8162 3 ปีที่แล้ว +6

      Can't you just do this?
      const data = await (await fetch(url)).json();

    • @roziscoding
      @roziscoding 3 ปีที่แล้ว +4

      @@akashchoudhary8162 you can, but IMHO it's the hardest one to read

    • @JonxuJJ
      @JonxuJJ 3 ปีที่แล้ว +2

      exactly, there is no real need to purposefully refactoring existing code to async/await.

    • @Javislaterlp
      @Javislaterlp 3 ปีที่แล้ว +10

      Lol no. Async await can and is meant to replace every then. I don't know if you meant it on a performance or readability POV but those intermediary variables you say replace the callbacks, which are also in memory, and variables are much more readable than anon funcs. JS is GC you shouldn't care about that; your concern is wrong but if you are concerned to that level use other lang.
      I would stare very weirdly to anyone who mixed then calls and await, seriously. If you are going to do that, keep chaining thens and ignore async/await altogether. The mix of both is the WORST posible scenario (in the same function obviously, not at a project level). Not to mention that if you have "a lot" of intermediary variables you are doing something completely wrong.

  • @hiteshsuthar1097
    @hiteshsuthar1097 2 ปีที่แล้ว +1

    Thank you

  • @moistbrownypoints
    @moistbrownypoints 2 ปีที่แล้ว

    Both are valid!

  • @FamousCloud
    @FamousCloud 2 ปีที่แล้ว

    Good stuff 👍

  • @sertansantos3032
    @sertansantos3032 2 ปีที่แล้ว

    Both valid, all preference

  • @yairv13
    @yairv13 3 ปีที่แล้ว +3

    I personally prefer the .then syntax, instead of multiple try-catch you can catch each promise easily. Async await is a new synthetic sugar that you don't have to use, but may.
    Plus you can use it on top level as well with no IIFEs or whatever.

    • @mykalimba
      @mykalimba 2 ปีที่แล้ว +1

      I think you mean syntactic sugar?

  • @SoftwareSolutons
    @SoftwareSolutons 3 ปีที่แล้ว

    But how can we figure out that exception occurred at the first promise , or at the second second promise?

  • @likwidsage
    @likwidsage 2 ปีที่แล้ว

    Do you need to await .map() when you already await-ed .all() and .map() isn't a promise?

  • @davidhainovitz2838
    @davidhainovitz2838 2 ปีที่แล้ว +1

    Just a small amendment : results.json() converts json to a js object not vice versa (13:18 )
    A quote from MDN web docs:
    Note that despite the method being named json(), the result is not JSON but is instead the result of taking JSON as input and parsing it to produce a JavaScript object.

  • @chart2023
    @chart2023 3 ปีที่แล้ว +1

    at 9:03, I cannot do like this, I got "await is only valid in async functions and the top level bodies of modules" with node 16

    • @RyanFlores9
      @RyanFlores9 2 ปีที่แล้ว

      Maybe because as the error states, you're using await in a function not declared as async, or you're not using await in a function at all. An example would be useful.