Tips For Using Async/Await in JavaScript

Поділитися
Вставка
  • Опубліковано 2 гру 2024

КОМЕНТАРІ • 458

  • @TheNelsonc24
    @TheNelsonc24 3 роки тому +16

    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 3 роки тому +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!

  • @TheDandef
    @TheDandef 3 роки тому +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.

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

  • @danielwisniewski5989
    @danielwisniewski5989 3 роки тому +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!

  • @rexxon1611
    @rexxon1611 3 роки тому +1

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

  • @Hertog_von_Berkshire
    @Hertog_von_Berkshire 3 роки тому +32

    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

  • @xpo11ox
    @xpo11ox 3 роки тому +3

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

  • @InsaneMetalSoldier
    @InsaneMetalSoldier 2 роки тому

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

  • @oneinazillion
    @oneinazillion 2 роки тому +7

    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

  • @jonathanroy72
    @jonathanroy72 3 роки тому +33

    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 3 роки тому +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 3 роки тому +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 2 роки тому

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

  • @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!

  • @stevenng1040
    @stevenng1040 2 роки тому

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

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

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

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

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

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

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

  • @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 "UA-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!

  • @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!! :)

  • @rolandodiaz3381
    @rolandodiaz3381 2 роки тому

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

  • @ricdotnet
    @ricdotnet 3 роки тому +1

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

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

  • @yb3985
    @yb3985 3 роки тому

    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.

  • @SaidElnaffar
    @SaidElnaffar 2 роки тому

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

  • @sordahl
    @sordahl 2 роки тому

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

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

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

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

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

  • @art_bat
    @art_bat 3 роки тому +1

    Both Promise sintaxes should be used interchangeably. Looking for readable code and beyond trivial cases, specifically with fine grained error handling, then/catch could also be preferable. I always decide on a case to case basis.
    There is problem when the async/await syntax is used to mask the fact (or not fully understanding) that you are dealing with promises.

    • @JamesQQuick
      @JamesQQuick  3 роки тому

      I haven't really found a use case for me to use .then instead of async/await, so I use it all the time.

  • @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 3 роки тому +1

      I think you mean syntactic sugar?

  • @jedirvine
    @jedirvine 3 роки тому

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

  • @varshasingh1299
    @varshasingh1299 3 роки тому +2

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

  • @bryanmora4996
    @bryanmora4996 2 роки тому

    I'd like to take a different approach when fetching and parsing to json, you can do await(await fetch(url)).json() and it will return the actual data in just a line of code

  • @AdamCole1
    @AdamCole1 Рік тому

    Really well explained. Thank you.

  • @harmmeijer6582
    @harmmeijer6582 3 роки тому

    A promise is a wrapped value that you can use for railway oriented programming, your code can be re used if the result is a promise or an async result represented as an object literal like in redux state because the important code is a function that receives a value and error, loading or stale is handled outside of that function.
    Functions should be doing only one thing so async await forces you to write functions that do more than the one thing and will make re usability and refactoring more difficult. It only looks "cleaner" because you write functions that do too much instead of composing multiple functions that do one thing.

  • @michaelvadney5803
    @michaelvadney5803 2 роки тому +1

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

  • @184Simon
    @184Simon 2 роки тому

    Perfect explanation!

  • @sabuein
    @sabuein Рік тому

    Thank you, James.

  • @elisasoto1
    @elisasoto1 3 роки тому

    Great explanation. Cristal clear

  • @Asli_
    @Asli_ 2 роки тому

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

  • @sak1b
    @sak1b 3 роки тому

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

  • @jazper808
    @jazper808 3 роки тому

    I wanna marry your code it looks so clean :)

  • @atiqbaqi
    @atiqbaqi 2 роки тому

    very helpful video, easy to understand

  • @RobertoGPuentesDiaz
    @RobertoGPuentesDiaz 3 роки тому

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

  • @cmtv357
    @cmtv357 2 роки тому

    This helped a lot. Thanks ma!

  • @SebastianStein85
    @SebastianStein85 3 роки тому

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

  • @BobbyBundlez
    @BobbyBundlez 2 роки тому

    The amount of hate in these comments and pestering nerds trying to one up is so funny. Relax guys. Thanks for the tutorial

  • @ewalshp
    @ewalshp 3 роки тому

    Thnak you. Excellent video.

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

  • @johnkeck
    @johnkeck 3 роки тому

    Very clear explanation! Thank you so much!

  • @juliusekandem
    @juliusekandem 3 роки тому

    Thank you soooo much!!! this really helped.

  • @maxtate906
    @maxtate906 3 роки тому

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

  • @CvetaMobi
    @CvetaMobi 2 роки тому

    Thank you!!!! Very understandable!

  • @nicknesler
    @nicknesler 2 роки тому

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

  • @SelmanIsHere
    @SelmanIsHere 2 роки тому

    Then, Catch imo is visually readable, it visually displays the sequence of actions, and forces you to plan on what data to pass to the next action.

  • @PFOctavio
    @PFOctavio 2 роки тому

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

  • @boem231
    @boem231 3 роки тому +2

    In the example of .then in the beginning, there's an error. Instead of "console.error(error) is should have been "console.error(err)"

  • @ivanmera1633
    @ivanmera1633 3 роки тому

    The fact that you and others have to explain how async/await works shows its main disadvantage: it can be confusing and prone to errors, whereas .then() is more human readable and easier to understand. Nevertheless, once you get the hang of it, you end up with very compact and clean code. I really like that. I'd only disagree with the use IIFE for top-level await; you end up with code that is harder to read.

    • @JamesQQuick
      @JamesQQuick  3 роки тому +1

      The asynchronous nature in and of itself is extremely confusing regardless of regular promises vs async/await. The need to explain how it works comes from the fact that it's new. Any new feature/syntax that is introduced into a language takes time to adopt and understand.

  • @bulletinmybeard
    @bulletinmybeard 2 роки тому

    Since I started writing a JS SDK a while ago, I’m using Promises with then/catch a lot and without running into issues like “unhandledrejection” which you should catch, regardless.
    Especially when using promises in class constructors where Async/Await is not an option.

  • @seismicoz
    @seismicoz 3 роки тому +5

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

  • @Kunal-jp8tn
    @Kunal-jp8tn 2 роки тому

    amazing tutorial thanks.

  • @Will2code
    @Will2code 2 роки тому

    If anyone is having trouble using and importing the node-fetch module, changing your files extension from .js to .mjs should do the trick. Alternatively you can also include
    "type": "module"
    in your nearest package.json file

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

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

  • @TheVisionBT
    @TheVisionBT 2 роки тому

    great tuto ! thank you!

  • @stainlesssteellemming3885
    @stainlesssteellemming3885 3 роки тому +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  3 роки тому

      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.

  • @tapantorbangla
    @tapantorbangla 3 роки тому

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

  • @Pareshbpatel
    @Pareshbpatel 2 роки тому

    Thanks, James

  • @gregclarkreasons
    @gregclarkreasons 3 роки тому

    Thank you for this awesome explanation and demonstration!

  • @yoonustehraniam8891
    @yoonustehraniam8891 3 роки тому

    Useful advice 👍

  • @smithscarborough
    @smithscarborough 3 роки тому

    Super helpful video. Thank you!

  • @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 3 роки тому

      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.

  • @igpekasuryawan
    @igpekasuryawan 3 роки тому

    Cool tips James. What is the benefit using Asycn await?

  • @raguilaru
    @raguilaru 3 роки тому

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

    • @RyanFlores9
      @RyanFlores9 3 роки тому +1

      Maybe in some scenarios, but not all.

  • @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 ^^

  • @PrimephotoStudio
    @PrimephotoStudio 3 роки тому

    Thank you for sharing this with us very helpful.

  • @sertansantos3032
    @sertansantos3032 2 роки тому

    Both valid, all preference

  • @raphaelmobistacla2236
    @raphaelmobistacla2236 3 роки тому +2

    Worth noting you didn't need to `await res.json()` or pass the mapped array to `Promise.all`. This only works because `await`ing a non-Promise value simply creates a new Promise and resolves immediately to the value `await`ed. You shouldn't do that, though.

    • @JamesQQuick
      @JamesQQuick  3 роки тому +1

      Ah shoot did I make that mistake? Great catch!

    • @RyanFlores9
      @RyanFlores9 3 роки тому

      I'm glad I wasn't the only who caught that. No wonder why I got confused and thrown off at that part of the video.

    • @PeerReynders
      @PeerReynders 2 роки тому

      Please note that response.json() returns a promise and therefore the await is necessary. The response object is available as soon as the headers have arrived - however the response body may not have yet arrived and been processed which is why response.json() has to be asynchronous.

  • @mraravind1111
    @mraravind1111 3 роки тому +1

    Hi, can you please help with my question that follows below 2 approaches of the same logic?
    Approach 1:
    const apiURls = ['url1','url2','url3'];
    (async ()=> {
    const result = await Promise.all(apiURLs.map(async(url)=> {
    await fetch(url)
    }));
    return result;
    })();
    Approach 2:
    const url1 = "url1", url2= "url2", url3=" url3";
    (async()=> {
    const result = await Promis.all([
    await fetch(url1), //step 1
    await fetch(url2), //step 2
    await fetch(url3) //step 3
    ]);
    return result;
    })();
    In the above two approaches, I see no difference in terms of their functionalities. However, why does only the 2nd approach seem to run in the sequence it is being called? (i.e url1 followed by url2 and url3) But, the 1st approach calls the fetch call randomly, and not in the sequence of the apiURLs array.

  • @ChrisLove
    @ChrisLove 3 роки тому

    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.

  • @sumitpandey7446
    @sumitpandey7446 2 роки тому

    Well sumed up mate

  • @555pontifex
    @555pontifex 2 роки тому

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

  • @cli23
    @cli23 3 роки тому

    Great explanation!

  • @jon1867
    @jon1867 3 роки тому +2

    I think a lot of people propagate this idea that Async/Await is better than ".then". It's not really cleaner it's just different.

    • @RyanFlores9
      @RyanFlores9 3 роки тому

      Error handling is especially different between the two approaches. I agree with you.

  • @DuncanMargetts
    @DuncanMargetts 3 роки тому

    Awesome! Thanks, learnt heaps.

  • @dgonch
    @dgonch 3 роки тому

    Great as always, thank you.

  • @vladometodiev3086
    @vladometodiev3086 Рік тому

    Thanks dude!

  • @rameshjp7045
    @rameshjp7045 3 роки тому

    Thanks a lot for sharing this! This really helped.

  • @pratyushkumar5740
    @pratyushkumar5740 3 роки тому

    Nice work♥️

  • @MatheusSouzaRigote
    @MatheusSouzaRigote 3 роки тому +1

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

  • @gustavo.paixao
    @gustavo.paixao 3 роки тому +3

    Really great content. When you start having multiples functions across multiple files handling promises gets hard as hell.

  • @markanthonylibres5113
    @markanthonylibres5113 3 роки тому

    I prefer using then, fail, catch, done... rather using await keyword for fetching data from a backend side, for me to validate response without using a conditional statement such as check the response if 200 etc.. and also to separate the process where what the program do if a request successfully make a responds or the request thrown an error or what to do if the request is successfully send to the server wether it is error or has a responds
    then ( ... successfully has a responds )
    fail ( ... has an error ... )
    done (... make a request ...)
    it is more cleaner, readable and easy to maintain

  • @mn42-x8
    @mn42-x8 Рік тому

    Awesome explanation!
    PS: high-level await doesn't work on Node v19.4.0

  • @dilshodturab
    @dilshodturab 2 роки тому

    thank you thank you you thank you you thank you you thank you you thank you you thank you you thank you you thank you you thank you you thank you you thank you you thank you i finally understand this

  • @mostinho7
    @mostinho7 Рік тому

    await keyword applied to a promise gets us the value asynchronously WITHOUT blocking
    const name = await getNamePromise();
    console.log(name); //name here will have the result available and not the promise object because we used await
    Await needs to be used inside an async function

  • @Abdallah_Ismail
    @Abdallah_Ismail Рік тому

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

  • @RichFinelli
    @RichFinelli 3 роки тому

    Nice explanation! I am always bummed though to use try / catch for error handling. I wish async / await had some better way to handle that. Thanks!

    • @RyanFlores9
      @RyanFlores9 3 роки тому

      Why? Try-catch should be used often in most/all programming languages. Heck, even SQL has try-catch error handling. It's usually a good idea to have an exception handler for specific scenarios.

    • @RichFinelli
      @RichFinelli 3 роки тому +1

      @@RyanFlores9 agreed that error handling and try / catch is key. I just like the .catch() method you can use with promises a little better. It’s cleaner. But you’re right try/catch not only works but is needed with async await. It doesn’t stop me from using async await over promises either.

  • @Tokur-zi7xf
    @Tokur-zi7xf 3 роки тому +3

    const content = James Q Quick
    const res= await fetch(content)
    console.log("GREAT STUFF!")