Async Await try-catch hell

Sdílet
Vložit
  • čas přidán 7. 06. 2021
  • Async Await is heaven... until error handling comes into play. Learn how to avoid try/catch hell when writing async JavaScript code.
    #shorts #js #programming
  • Věda a technologie

Komentáře • 1,1K

  • @gabriel.quagliano
    @gabriel.quagliano Před 3 lety +4623

    Protip: Avoid the pyramid of doom by never indenting your code 🤙.

    • @claudeb.3473
      @claudeb.3473 Před 3 lety +363

      Why stop there? Eliminate errors by disabling lint rules and git hooks. Some of our developers are getting a lot done using these techniques.

    • @rexygama7697
      @rexygama7697 Před 3 lety +19

      Bruh

    • @sertanojouniversiotario9599
      @sertanojouniversiotario9599 Před 3 lety +9

      @@claudeb.3473deactivate lint? For me lint does nothing but helping with some details with the code. I use intellij editor. I can code without lint very well. But I maintain it active cuz it's kinda cool. But totally unnecessary for the code to compile. Of course the intelijj editor helps to get the job done.

    • @PMA65537
      @PMA65537 Před 3 lety +181

      @@sertanojouniversiotario9599 What version of is_joke() do you have?

    • @Just_Moh_it
      @Just_Moh_it Před 3 lety +34

      @@PMA65537 I think we'll have to run $ bad_joker --v

  • @lvenir4702
    @lvenir4702 Před 3 lety +1106

    "a sink"
    "a weight"
    k

  • @tdubab
    @tdubab Před 3 lety +3303

    Basically you made Javascript looks like Golang Lol.

    • @febrilian
      @febrilian Před 3 lety +177

      yeah golang ftw, peak of simplicity

    • @okie9025
      @okie9025 Před 3 lety +60

      and Rust

    • @xetera
      @xetera Před 3 lety +125

      @@okie9025 Rust does not do error handling this way

    • @okie9025
      @okie9025 Před 3 lety +123

      @@xetera it uses Result to wrap errors with return values lol. You can even do ".unwrap()" to throw the error and stop execution.

    • @framepointer
      @framepointer Před 3 lety +141

      @@okie9025 using a Result enum with functions for handling the data is much more pleasing than the golang way of checking for nil everytime lol

  • @wumbl3
    @wumbl3 Před 3 lety +850

    My life is pretty dull and uneventful, so this was the best 45 seconds of my life.

    • @hdluktv3593
      @hdluktv3593 Před 3 lety +17

      It's not. You decide what an event is four you and what not.

    • @mandrasaptakmandal636
      @mandrasaptakmandal636 Před 3 lety +7

      add some css to ur life.... or import Bulma

    • @naveenkr5992
      @naveenkr5992 Před 3 lety +6

      const EventEmitter = require('events') ;
      const event = new EventEmitter () ;
      event.on('event', message => console.log(message) ;
      While(true) event.emit('event', 'You're having a "eventful" life (literally)') ;

    • @AmxCsifier
      @AmxCsifier Před 3 lety +2

      You got 100 likes so now your life is pretttttty good

    • @EricLatios
      @EricLatios Před 3 lety +1

      your life is undefined, and the undefined life is not worth living

  • @alexeyl1739
    @alexeyl1739 Před 3 lety +802

    Congrats! You one step closer to using monads for error handling

    • @Fireship
      @Fireship  Před 3 lety +251

      We'll get there someday

    • @NightstalkerKK
      @NightstalkerKK Před 3 lety +10

      Do you have an example of this error handling implemented in javascript? i would like to look at it, thank you

    • @alexeyl1739
      @alexeyl1739 Před 3 lety +39

      @@NightstalkerKK Well, if you go down that rabbit hole and make an Either-monad that can be either DATA or ERROR you'll get something very simmilar to Promises (which are basically monads ), and I'm not sure why someone would want to do that. That's not a sarcasm. I want to know why someone would want to do that.

    • @RicardoValero95
      @RicardoValero95 Před 3 lety +9

      @@alexeyl1739 aren’t you describing TaskEither from fp-ts (I’m not saying they invented it)

    • @alexeyl1739
      @alexeyl1739 Před 3 lety +8

      @@RicardoValero95 No, havn't tried fp-ts yet, just general Ether monad. It can be Maybe (or Option) monad depending on how you look at it.
      I'm not a computer scientist so feel free to corect me

  • @truedarkness728
    @truedarkness728 Před 3 lety +1238

    the best 45 seconds of my life

    • @namansinghal1892
      @namansinghal1892 Před 3 lety +88

      That's what she said

    • @hojdog
      @hojdog Před 3 lety +7

      *Almost* the best 45 seconds of my life, second only to making love to my wife

    • @thinclient5318
      @thinclient5318 Před 3 lety +6

      You and me both.

    • @12px
      @12px Před 3 lety

      True.

    • @TheJachi97
      @TheJachi97 Před 3 lety +1

      @@namansinghal1892 u.u

  • @erbesharat
    @erbesharat Před 3 lety +179

    This reminds me of a quote:
    "Errors are values"

    • @adrycough
      @adrycough Před 3 lety +76

      I guess that makes me very valuable

    • @kyutifer
      @kyutifer Před 3 lety +10

      @@adrycough bruh

    • @trejohnson7677
      @trejohnson7677 Před 2 lety +5

      *laughs in c*

    • @Rudxain
      @Rudxain Před 2 lety +4

      In Javascript, errors are objects, and objects are containers of values, and therefore data

  • @arwahsapi
    @arwahsapi Před 3 lety +98

    I've been asynchronously awaiting for this and finally this video showed up

  • @Toleich
    @Toleich Před rokem +42

    And we're coming full circle.

  • @bensas42
    @bensas42 Před 3 lety +142

    Holy shit, most youtubers would have turned this into a 10 minute monetized video. You are amazing.

    • @ihateidiots9484
      @ihateidiots9484 Před 4 měsíci

      No, he is not. He suggests incorrect solution. Simple solution:
      async func() {
      try {
      const a = await step1();
      const b = await step2(a);
      const c = await step3(b);
      return a + b + c;
      } catch (e) {
      handle(e);
      throw e;
      }
      }

    • @davguev
      @davguev Před 3 měsíci

      ​@@ihateidiots9484Implying you want the same error handling for every step.

    • @ihateidiots9484
      @ihateidiots9484 Před 3 měsíci

      @@davguev his error handling is wrong because in case of first error "a" variable is still undefined, so step2(a) makes no sense. The same is for "b" variable. My refactoring fixes this problem

  • @rumplstiltztinkerstein
    @rumplstiltztinkerstein Před 3 lety +45

    rust developers can just put ? in front of the function. If an error occurs, the function halts and returns the error. It's awesome for those that understand it, a nightmare for someone unfamiliar with rust lol.

    • @MrMudbill
      @MrMudbill Před 2 lety +1

      Is that also the case for async code in Rust? Async is inherently different. JS does have the ? on objects to continue if something exists, otherwise returns undefined, which sounds similar to what you're describing.

    • @rumplstiltztinkerstein
      @rumplstiltztinkerstein Před 2 lety +6

      @@MrMudbill interesting. Thanks for that, I'm still really bad at js. In rust, we have enums that specify a limited number of data types. These enums can wrap other types of objects.
      There are no exceptions in Rust. Everything that can return an error is represented by an enum called Result. This enum can be Ok or Error, A is the type of the object that represents the succesful result. B is the type that is returned when something goes wrong, can be a string with a text like "failed to do x", but often it's another enum representing all kinds of possible reasons for an error to occur.
      The good thing about this is that every possibility is already pre-compiled and optimized. ? just unwraps the Ok or return Error for the function.
      Async rust doesn't change the return values of the functions.

    • @jpratt8676
      @jpratt8676 Před rokem +2

      After the function arguments but yeah... And I promise that getting used to it is easier than learning exceptions

  • @Ipauler
    @Ipauler Před 3 lety +57

    And then you will end up with tower of ifs, when each function depends on previous results
    You've just writed try catch using if statements nothing changed
    What you can do is catch them all together
    And make specific errors for each function and then switch through errors in catch block if you need to perform something for each error case

    • @MrMudbill
      @MrMudbill Před 2 lety +12

      Early returns are nice

    • @cryonim
      @cryonim Před 2 lety +5

      That is also the same thing, you've just shifted the try catches into ifs inside a catch.
      My solution would be to have a single function with a try catch, it would call a function passed to it and return null or data based on exception. Basically, a wrapper function. So now all you need to do is call this function and pass it whatever async function you have and it will either return null or data and you can check it easily.

  • @monkeyinadrawer
    @monkeyinadrawer Před 3 lety +149

    So from tower of doom with try/catches to tower of doom with if/elses?

    • @alexey-ym
      @alexey-ym Před 2 lety +11

      And to tower of doom with functions for every "step" and try catch inside

    • @TheDaidalosKvintus
      @TheDaidalosKvintus Před 2 lety +6

      Not quite… the tower of doom is necessary since without it your code would break and stop executing (without a catch) .
      With this approach you can decide what to do with the error if you wish to but your code won’t stop running.
      Of course you could use top level try catch but that takes await the granularity of handling the errors which this approach provides.

    • @rb1471
      @rb1471 Před rokem +1

      @@TheDaidalosKvintus How does a top level try/catch work with multiple? I would assume if one crashes the rest stop processing, otherwise you'd be catching multiple errors if more than one breaks. So I don't think a top level try/catch actually works

  • @Vaidd4
    @Vaidd4 Před 3 lety +17

    Tips:
    - Make the function take a promise as a parameter
    - use "catch" method of the promise
    - Call this function "to"
    function to (promise) {
    return promise.then(data => [null, data]).catch(err => [err])
    }
    const [err, data] = await to(fetch(/*thatUrl*/))
    Notes: Dont need to have an async function or to use try-catch; its reusable for any function returning a promise; its a oneliner in a oneliner \o/

  • @omararmandourquidezcastro7327

    To use the "awesome" function in typescript, you can do it like this:
    async function awesome (
    prom: Promise
    ): Promise {
    try {
    return [await prom, null];
    } catch (error) {
    return [null, error];
    }
    }

  • @cat-.-
    @cat-.- Před 3 lety +70

    You still have to if (data !== null) every time if you want your program to have any decent behaviour though.

    • @bash7279
      @bash7279 Před 3 lety +8

      You can use
      data && console.log("data isn't null")
      For a one liner or just
      If(data) {}
      So it's just more cleaner than try catch

    • @cat-.-
      @cat-.- Před 3 lety +24

      @@bash7279 What if your data can be 0? What if `false` is a valid data? That's why it always has to be !==

    • @lord_kh4n
      @lord_kh4n Před 3 lety

      @@cat-.- Well, if (data !== null) is still technically one liner

    • @0xlogn
      @0xlogn Před 3 lety +16

      @@bash7279 But then you end up with stuff like
      async function foo() {
      let [res, err] = await bar();
      if (res) {
      let [r2, e2] = await baz();
      if (r2) {
      // ...
      }
      }
      }

    • @cat-.-
      @cat-.- Před 3 lety +22

      @@0xlogn you can use guard pattern:
      let [data, err] = await step1()
      if (err) return err
      let [data2, err2] = await step2()
      ...

  • @TheHy6xD
    @TheHy6xD Před 3 lety +6

    Swift just got Async/ Await feature and now I'm getting this as recommended.

  • @ShreksSpliff
    @ShreksSpliff Před 3 lety +32

    So imagine when we realise that we could be adopting a functional paradigm and we can live inside of a monad

    • @LoveLearnShareGrow
      @LoveLearnShareGrow Před 3 lety +23

      Every time I look up the definition of monad, I forget it by the next time I see the word mentioned again.

    • @redpepper74
      @redpepper74 Před 2 lety +4

      @@LoveLearnShareGrow Huh, Wikipedia actually has a pretty concise definition for it:
      “In functional programming, a monad is a type that wraps another type and gives some form of quality to the underlying type.”

    • @LoveLearnShareGrow
      @LoveLearnShareGrow Před 2 lety +5

      @@redpepper74 Yup. That is extremely forgettable.

    • @Rudxain
      @Rudxain Před 2 lety +2

      @@redpepper74 that seems like a very ambiguous definition. Is a monad a value of a custom data type or is it the data type itself?. Are monads comparable to Javascript objects since they can "wrap" primitive values? What "quality" is given to the wrapped object/value? Does this ambiguity exist because monads are meant to be versatile and therefore it's an umbrella term?

    • @Steve-hd5tn
      @Steve-hd5tn Před rokem +9

      A monad is just a monoid in the category of endofunctors, what's the problem?

  • @oglothenerd
    @oglothenerd Před 5 měsíci +4

    Return error as value is amazing. I love Rust.

  • @beorntwit711
    @beorntwit711 Před 3 lety +3

    Such a quality of life improvement. I read this in an article once, when I was just starting out, and started writing it, just waiting for the other shoe to drop (I had to defend it before my boss, who was skeptical at first, even though he hated try catch and longed for the async.js days); cause why wasn't everyone doing this? No regrets!

  • @ihateorangecat
    @ihateorangecat Před 8 měsíci +3

    The solution I ever Needed.

  • @jordinario
    @jordinario Před 3 lety +73

    Nice tips! This applies to Golang as well and it's error handling nightmare

    • @thechargeblade
      @thechargeblade Před 3 lety +3

      Doesn't Go has default multiple return value?

    • @omarelkhatib150
      @omarelkhatib150 Před 3 lety +33

      most people say its a hell , but its necessary to not be lazy with errors. GoLang is protecting us from ourself. Errors are values so take advantage of that.

    • @Hyperlands
      @Hyperlands Před 3 lety

      @@omarelkhatib150 True, but the downside is that our code can break fully on production

    • @jordinario
      @jordinario Před 3 lety +3

      reminder that when Generics arrive, you'll be able to be ultra lazy and do stuff like this without any interface conversion
      func catch[T any](val T, err error) T {
      if err != nil {
      log.Error(err)
      }
      return val
      }
      and call it like: var x int = catch(strconv.Atoi("lol not a number"))

    • @atkevindsouza
      @atkevindsouza Před 3 lety +1

      @@Hyperlands How so?

  • @cameron2027
    @cameron2027 Před 4 hodinami

    This is creeping toward a design pattern of functional programming, where functions take in an error state as an extra parameter, and also return an error state within the return type. If there’s an error passed in, it’ll just early return the error. If the function itself encounters an error, it’s included in the returned payload. Otherwise, it just returns the expected output. This way, you can chain functions in any order and ensure that an error will get caught early and allow downstream functions to skip expensive logic. Once I learned this pattern, I started using it everywhere. So useful.

  • @Appl3Muncher
    @Appl3Muncher Před 2 lety +1

    The difference is honestly astounding. I want to get better at writing clean JavaScript code thanks.

  • @javohirmirzo
    @javohirmirzo Před 3 lety +16

    Instead of attaching catch to each function, how about putting all await functions inside one try catch? Would that work?

    • @fadhilimalongo9910
      @fadhilimalongo9910 Před 2 lety +6

      Yes it does.. but you might find yourself using if else on the catch block or a switch statement in order to target a specific error

  • @catherineepps9175
    @catherineepps9175 Před 3 lety +4

    I'm starting to love programming. I enjoy it now. I understand it now.

    • @scidja8567
      @scidja8567 Před 2 lety

      how can you understand it? to me it seems like all the codes need to be memorized

    • @thecoolnewsguy
      @thecoolnewsguy Před měsícem

      ​@@scidja8567nah just Google stuff

  • @dkosmari
    @dkosmari Před 3 lety +1

    Looks a lot like Andrei Alexandrescu's "Expected" from his 2012 talk. It's a variant that stores either the value, or an exception. But C++'s operator overloading makes it more convenient to use.

  • @maxpowers1015
    @maxpowers1015 Před 3 lety +1

    Absolutely love the conciseness

  • @godbleak
    @godbleak Před rokem +3

    Made this into the package resolvjs, with first class TypeScript support.

  • @code4chaosmobile
    @code4chaosmobile Před 3 lety +3

    i remember my excitement when the feature was making its way to stable, so much code back then..
    i'm not crying, your crying :'(

  • @nguyenvanthang7387
    @nguyenvanthang7387 Před 3 lety +2

    We need more quick tips like this. Thanks so much

  • @maxmonciardini
    @maxmonciardini Před 2 lety +1

    I never thought about doing it this way but thats super clean! Definitely going to try this out

  • @modeck5844
    @modeck5844 Před 3 lety +142

    hello from golang:)

    • @t_kon
      @t_kon Před 3 lety +11

      coming from c to javascript to python and recently to golang, I'll have to admit I like the way golang handles errors.

    • @shravanshetty347
      @shravanshetty347 Před 3 lety +10

      @@t_kon Yes, just handle all the errors omegalol

    • @climatechangedoesntbargain9140
      @climatechangedoesntbargain9140 Před 3 lety +2

      @@t_kon rust is another upgrade here

  • @arson5304
    @arson5304 Před 3 lety +22

    i l;ove u jeff

  • @php1036
    @php1036 Před 2 lety +2

    I like how there are pictures of a sink and a weight in the beginning

  • @IamPali2024
    @IamPali2024 Před 5 měsíci

    You can pay for a course with MasterCard but “The sink and the weight”: priceless 😂

  • @n0xter95
    @n0xter95 Před 3 lety +10

    Ok now I can add try-catch handling to my CV

  • @zugdsbtngizudsgbnudsdsoiu
    @zugdsbtngizudsgbnudsdsoiu Před 3 lety +18

    After finally defeating the Pyramid of Doom another foe has risen out of the depths of the binary system.
    The Tower of Terror.

  • @ajaysihota2299
    @ajaysihota2299 Před 3 lety

    Love these short, to the point videos!

  • @ischysyt
    @ischysyt Před 3 lety +1

    I literally studied this yesterday, nice refresher on it for me, thanks Fİreship!

  • @JKCD
    @JKCD Před 3 lety +5

    Teaching something so awesome in 45secs. You're on whole another level.

  • @TobiSGD
    @TobiSGD Před rokem +37

    You know a language is broken when you have to implement a workaround to a workaround to a workaround.

    • @sayamqazi
      @sayamqazi Před rokem +1

      or the language was made when there was no need to do gazillion things in the web-browser.

    • @fbarnea
      @fbarnea Před 8 měsíci

      ​@@sayamqazithat's not an excuse, there are plenty of examples of languages that have withstood the test of time much better because they were built on solid principles

    • @sayamqazi
      @sayamqazi Před 8 měsíci +1

      @@fbarnea but again the guy building the language didn't foresee what it was gonna be used for. And from what i recall he did it in a couple weeks. Nobody was expecting full fledged apps were gonna run in browsers. But once the web exploded it was not easy to backtrack and fix the issues as a lot of code was already shipped. this is exactly why broken html actually renders somewhat fine in the browsers to this day.

    • @fbarnea
      @fbarnea Před 8 měsíci

      @@sayamqazi that doesn't contradict the fact that the language is broken. What you are saying just further solidifies that it's broken and not fit for purpose. Yet anytime someone says this countless fanboys feel the need to contradict.

    • @sayamqazi
      @sayamqazi Před 8 měsíci +1

      @@fbarnea but where did i contradict. i just extended the discussion and made a point that things are not as bleak as some people make them look like. after all it has been serving it purpose to billions of users every day. it has added hundreds of billions of dollars of value to the economy not out of nothing. yes it needs to and can improve but people do exist on each side of the extreme. javascirpt is literally the goto langauge to take shots on for many people.

  • @phoenixshell3772
    @phoenixshell3772 Před 2 lety

    Just what I need, I just learned how to use async JavaScript probally and now this is my problem. Super useful

  • @eduardopina7964
    @eduardopina7964 Před 3 lety

    You probably should make a video for the rest of CZcams(rs) on how to provide so much value in a so short amount of time... amazing

  • @kettenbach
    @kettenbach Před 3 lety +7

    Lmfao a sink a weight. Frikin love you bro. 😀🙌👑🔥🚀

  • @parthipankalayini8
    @parthipankalayini8 Před 3 lety +9

    Haha started to learn go lang after watching net ninja now tips from fireship ♥❤♥

  • @philfreshman
    @philfreshman Před 3 měsíci

    The last option is that classic Golang approach of handling errors, I highly recommend it 🤘🏻

  • @lbirkert
    @lbirkert Před 2 lety

    You just changed my life

  • @WorstDeveloper
    @WorstDeveloper Před 3 lety +19

    This feels a lot like how Go works. Did you draw inspiration from it?

    • @vincent-thomas
      @vincent-thomas Před 2 lety +2

      No, react hooks has the same format, kinda

    • @jpratt8676
      @jpratt8676 Před rokem +1

      And why would you? This blows up the number of things to have to consider at one point in the code, just for a syntactic nicety.

  • @dkaraush
    @dkaraush Před 3 lety +36

    if you have the same handler for all those functions why you can't put a try-catch over that function you are writing?
    that's ok when your function can throw something, that's just natural js behavior (rather than onError callbacks)

    • @mattshnoop
      @mattshnoop Před 3 lety +10

      I think the point here is that this can be used when you have different handlers, even if he uses the same `handler` function in this example.

  • @arthurbm32
    @arthurbm32 Před 4 měsíci

    That's why Tanstack query is so valuable in JavaScript

  • @sidheshwartiwari9834
    @sidheshwartiwari9834 Před rokem +1

    Seeing this pattern being used in multiple modern libraries lately. 🔥🔥

  • @ebeltran
    @ebeltran Před 2 lety +3

    You have to pass the promise as an argument in the awesome function, right? otherwise the code wouldnt work

  • @vianch_tog
    @vianch_tog Před 3 lety +6

    I love the end of this video!!

  • @cas818028
    @cas818028 Před rokem

    Thank you for reinventing GO

  • @hannibal.b5242
    @hannibal.b5242 Před 3 lety

    the quality of the videos... this man is a genius 👍👍👍

  • @temoncher
    @temoncher Před 3 lety +19

    Get some functional programming patterns into your object oriented weekdays a passing by programmer

    • @buraky16
      @buraky16 Před 3 lety

      do you have any suggestion for a static typing functional language to learn?

    • @temoncher
      @temoncher Před 3 lety +1

      @@buraky16 talking about frontend - Elm is good and friendly. On BE side it's either f# (if you want to have an ability to retreat into OOP sometimes) or haskel (if you want to go full hardcore).

  • @jediampm
    @jediampm Před 3 lety +6

    hi, if you have sequence of promises like your example, i would use promise.all() and put there all the previous promises as args and the inside one try catch. LOL ;)
    Next video Top level await in browser and nodeJS ( its is now available in FF and all chromium browser) ;)

    • @asm5087
      @asm5087 Před rokem

      Yes but thats a little complicated procedure for those who dont know about it, to be explained in a short video, dontya think

    • @jediampm
      @jediampm Před rokem +1

      @@asm5087 No. Because is not the correct way.
      If one promise dont depend on another then you should use promise.all.
      I recommend read mdn to see the difference.

  • @brandonz404
    @brandonz404 Před 3 lety

    I dont know where all these coding shorts came from but I'm loving them

  • @davedave9924
    @davedave9924 Před rokem +1

    My guy basically created Result type.

  • @AlexAegisOfficial
    @AlexAegisOfficial Před 3 lety +8

    or, embrace the power of RxJS and the observables! Join the dark side!

    • @NightstalkerKK
      @NightstalkerKK Před 3 lety +1

      do you have an example of handling errors with rxjs, id like to look at it

    • @iM7SnaKe
      @iM7SnaKe Před 3 lety

      @@NightstalkerKK put a catch inside pipe. Done

    • @VelGoesBrrr
      @VelGoesBrrr Před 3 lety

      @@iM7SnaKe And you can forkJoin observable calls to avoid nesting calls

    • @AlexAegisOfficial
      @AlexAegisOfficial Před 3 lety

      @@NightstalkerKK pretty sure you can find one but in a nutshell you can catch errors with a catchError operator. If an error occurs in a pipe it just flies straight to the next catchError, its a higher order operator like switchMap and you can gracefully recover from it. If an error is not catched it errors the whole pipeline (dont forget that multicasting segments the pipelines), and shuts down the subscription.

    • @AlexAegisOfficial
      @AlexAegisOfficial Před 3 lety +1

      @Pasha Bolokhov that really doesnt matter, rxjs is a low level library, a set of tools to solve async programming. While promises only hold one future value, observable hold N future values. And actually a lot of things support it because its popular (Angular, Svelte). The "integration" you're talking about is just whether or not that something has built in solution to handle subscriptons, which is really only needed in templates.
      And there is an RFC to include observables as native JavaScript constructs :)
      Protip: try to keep manual subscriptions as low as possible and instead create pipelines, taps, and utilize multicasting and higher order operators

  • @zyansheep
    @zyansheep Před 3 lety +15

    Me, who uses Rust: ?

    • @totto6868
      @totto6868 Před rokem +2

      rust ftw, just slap a ? on that bad boy

  • @MaxFerney
    @MaxFerney Před 3 lety +1

    I ran into both issues. THANK YOU

  • @NetherFX
    @NetherFX Před rokem

    this is what's called an iCallback, very useful when setting up anything with complex error handling. I've used it for android projects before and it's a blessing!-

  • @Intrevel
    @Intrevel Před 3 lety +3

    I'm still a super beginner but I just know this'll come in handy in the future!
    probably!

  • @maltegb
    @maltegb Před 3 lety +31

    could you not just put multiple async calls in one try catch like this:
    try{
    const a = await asyncCall()
    const b= await asyncCall()
    const c = await asyncCall()
    }catch{}

    • @emko333
      @emko333 Před 3 lety +19

      yes but if "a" errors the next b and c wont run .... you might just want to handle errors for each

    • @raenastra
      @raenastra Před 3 lety +9

      You could, but if a function throws an error here, the following function calls won't get executed. You'd have to put each function in its own try/catch, which is where the video starts from

    • @MartinOmander
      @MartinOmander Před 3 lety +12

      I agree; I use a single try-catch when each operation uses the output of the previous one. If the first operation fails, most of the time it doesn't make sense to run subsequent operations without inputs.

    • @daheck81
      @daheck81 Před 3 lety +10

      How about using Promise.all([asyncCalls]) (or Promise.allSettled([asyncCalls]) if the calls do not depend on each other). This is better then chaining awaits

    • @MartinOmander
      @MartinOmander Před 3 lety +3

      @@daheck81 Agreed, Promise.all() is far more efficient if the asynchronous operations don't depend on each other.

  • @vader567
    @vader567 Před 12 dny

    Love how the core just says “welcome” 😂💀

  • @phuocquang2314
    @phuocquang2314 Před 3 lety

    Love content like this, keep it up Fireship ❤

  • @rhysvanderwaerden5518
    @rhysvanderwaerden5518 Před 3 lety +3

    A fine pattern for sure (and not specific to async). But a more idiomatic approach would be to switch on error type, wrapping the entire block in a single try/catch.

  • @above-us
    @above-us Před 3 lety +3

    Your videos make me feel dumb. Thank you!

  • @cloudkungfu
    @cloudkungfu Před 3 lety +2

    React hooks for async await. This is next level

  • @LordVodka313
    @LordVodka313 Před 2 lety

    This was a godsend GODMODE PRO-CODER MOVE
    MINDBLOWN!!

  • @chavdarslavov3731
    @chavdarslavov3731 Před 3 lety +7

    Any reason you want to try/catch every line separately?

  • @polrk
    @polrk Před 3 lety +3

    Hi^ golang

  • @atleast_me
    @atleast_me Před 2 lety

    I usually don't subscribe randomly, but you are the guy didn't leave me an option to go without subscribe.

  • @pupinarvaja
    @pupinarvaja Před 2 lety

    This helped me to understand so many things... thank you so much

  • @RohitKumar-xs3wh
    @RohitKumar-xs3wh Před 3 lety +5

    first

  • @beamer5404
    @beamer5404 Před 3 lety +3

    How good practice is it to append catch with await?
    await something().catch(err=> ())
    Can anybody tell me about this, it looks to be not a good practice

    • @kalleguld
      @kalleguld Před 3 lety +2

      If you can actually handle and recover from the error then it's fine. if you just throw away the error and pretend it didn't happen, you're in for a surprise and a hard time debugging.

    • @SimonBuchanNz
      @SimonBuchanNz Před 3 lety

      In my opinion it's the best way to express that specific behavior. Just make sure you actually want and can handle the result from either something or the catch body result if it isn't rethrowing in that body.
      Keep in mind, async/await is defined in terms of those Promise methods: there's no issues crossing the streams here.

  • @DaniloJr
    @DaniloJr Před 2 lety

    This remembers me the Either that is a built-in feature in functional programming languages. Great content, man!

  • @myk3_
    @myk3_ Před 9 měsíci

    Okay this is the most useful video i e watched today ❤

  • @alexleung842
    @alexleung842 Před 3 lety +4

    fp-ts Either construct. Also see how Rust does it.

  • @titusfx
    @titusfx Před 3 lety +5

    RxJS

  • @fredhair
    @fredhair Před 3 lety +2

    If you want an error to break the sequence of events you should probably be wrapping the multiple await calls in the same try / catch block ? You can always check the error instanceof if you need to know which error type occurred. That's probably what I would do.

  • @Mark98T
    @Mark98T Před 3 lety

    thank you for this very useful short video. Subscribed!

  • @jpmitchell925
    @jpmitchell925 Před 3 lety

    This was the most efficient program video I have ever witness

  • @ftwgamezone1961
    @ftwgamezone1961 Před 3 lety

    Thank you Jeff🙏.Now my code will be clean🤗.
    async function resolvePromise(promise) {
    try {
    const data = await promise;
    return [null, data];
    } catch (error) {
    return [error, null];
    }
    }

  • @muhamadzidan317
    @muhamadzidan317 Před 3 lety

    Man we need more tips like this ! its awesome

  • @mathematical-guy1728
    @mathematical-guy1728 Před rokem

    Being new to JS, I was scared of promises, async-await and tower_of_terror, you are LIFE SAVER !!!

  • @jhanke10
    @jhanke10 Před 3 lety +1

    There is a npm package await-to-js that does this. Love this concept.

  • @KangoV
    @KangoV Před 3 měsíci

    Ahh, look at the new "Structured Concurrency" coming in Java. It solves this brilliantly.

  • @LongBoy.0
    @LongBoy.0 Před 3 lety

    Love this channel

  • @dianlabuschagne2239
    @dianlabuschagne2239 Před 3 lety +1

    is it just me that actually prefers .then and .catch? - It just makes it clear in my mind what a function is doing and going to do if it errors

  • @jeffleigh5291
    @jeffleigh5291 Před 3 lety

    Wow! Mind blown! How about a full length video on how to avoid this. Can't wrap my head around it...

  • @0shawhat
    @0shawhat Před 3 lety

    Still learning JavaScript and I'll be sure to make note of this!!

  • @julkul99
    @julkul99 Před 9 měsíci

    Neat trick, this looks a lot like GO. You will then ofc have to check for errors like in GO after getting them back in the array.

  • @zoltanmatok1928
    @zoltanmatok1928 Před 3 lety

    How did I not know this? This is awesome, thank you!

  • @gerryramosftw
    @gerryramosftw Před 3 lety

    this is the video that i didn't know i needed but always did

  • @GetAnswerly
    @GetAnswerly Před 3 lety +1

    We've come full circle

  • @hectorrubio1474
    @hectorrubio1474 Před rokem

    There's a library called await-to-js that does that, but it's absolutely better implement it by our own, thanks 👍

  • @kszyh_
    @kszyh_ Před 3 lety

    Quick and awesome. More tips like this one!