Async Await try-catch hell

แชร์
ฝัง

ความคิดเห็น • 1.1K

  • @gabriel.quagliano
    @gabriel.quagliano 3 ปีที่แล้ว +4662

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

    • @claudeb.3473
      @claudeb.3473 3 ปีที่แล้ว +366

      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 3 ปีที่แล้ว +19

      Bruh

    • @sertanojouniversiotario9599
      @sertanojouniversiotario9599 3 ปีที่แล้ว +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 3 ปีที่แล้ว +182

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

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

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

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

    Basically you made Javascript looks like Golang Lol.

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

      yeah golang ftw, peak of simplicity

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

      and Rust

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

      @@okie9025 Rust does not do error handling this way

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

      @@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 3 ปีที่แล้ว +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

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

    "a sink"
    "a weight"
    k

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

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

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

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

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

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

    • @naveenkr5992
      @naveenkr5992 3 ปีที่แล้ว +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 3 ปีที่แล้ว +2

      You got 100 likes so now your life is pretttttty good

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

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

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

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

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

      We'll get there someday

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

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

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

      @@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 3 ปีที่แล้ว +9

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

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

      @@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 3 ปีที่แล้ว +1242

    the best 45 seconds of my life

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

      That's what she said

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

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

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

      You and me both.

    • @12px
      @12px 3 ปีที่แล้ว

      True.

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

      @@namansinghal1892 u.u

  • @Toleich
    @Toleich ปีที่แล้ว +46

    And we're coming full circle.

    • @AB-yn2rz
      @AB-yn2rz 6 หลายเดือนก่อน +2

      😂

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

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

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

      Promise fulfilled.

    • @davidt01
      @davidt01 7 หลายเดือนก่อน

      ​@@floobertuber*resolved

    • @zachkurdi3178
      @zachkurdi3178 3 หลายเดือนก่อน

      Have you heard of golang, or monads 😅

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

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

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

      I guess that makes me very valuable

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

      @@adrycough bruh

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

      *laughs in c*

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

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

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

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

    • @ihateidiots9484
      @ihateidiots9484 4 หลายเดือนก่อน

      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 4 หลายเดือนก่อน

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

    • @ihateidiots9484
      @ihateidiots9484 4 หลายเดือนก่อน

      @@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 3 ปีที่แล้ว +46

    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 2 ปีที่แล้ว +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 2 ปีที่แล้ว +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 ปีที่แล้ว +2

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

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

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

    • @alexey-ym
      @alexey-ym 3 ปีที่แล้ว +11

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

    • @TheDaidalosKvintus
      @TheDaidalosKvintus 2 ปีที่แล้ว +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 ปีที่แล้ว +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

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

    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 2 ปีที่แล้ว +12

      Early returns are nice

    • @cryonim
      @cryonim 2 ปีที่แล้ว +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.

  • @oglothenerd
    @oglothenerd 5 หลายเดือนก่อน +4

    Return error as value is amazing. I love Rust.

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

    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-.- 3 ปีที่แล้ว +70

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

    • @bash7279
      @bash7279 3 ปีที่แล้ว +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-.- 3 ปีที่แล้ว +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 3 ปีที่แล้ว

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

    • @0xlogn
      @0xlogn 3 ปีที่แล้ว +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-.- 3 ปีที่แล้ว +22

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

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

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

    • @LoveLearnShareGrow
      @LoveLearnShareGrow 3 ปีที่แล้ว +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 2 ปีที่แล้ว +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 2 ปีที่แล้ว +5

      @@redpepper74 Yup. That is extremely forgettable.

    • @Rudxain
      @Rudxain 2 ปีที่แล้ว +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 ปีที่แล้ว +9

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

  • @Vaidd4
    @Vaidd4 3 ปีที่แล้ว +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/

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

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

  • @ihateorangecat
    @ihateorangecat 8 หลายเดือนก่อน +3

    The solution I ever Needed.

  • @beorntwit711
    @beorntwit711 3 ปีที่แล้ว +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!

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

    hello from golang:)

    • @t_kon
      @t_kon 3 ปีที่แล้ว +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 3 ปีที่แล้ว +10

      @@t_kon Yes, just handle all the errors omegalol

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

      @@t_kon rust is another upgrade here

  • @cameron2027
    @cameron2027 4 วันที่ผ่านมา

    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.

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

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

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

      Doesn't Go has default multiple return value?

    • @omarelkhatib150
      @omarelkhatib150 3 ปีที่แล้ว +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 3 ปีที่แล้ว

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

    • @jordinario
      @jordinario 3 ปีที่แล้ว +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 3 ปีที่แล้ว +1

      @@Hyperlands How so?

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

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

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

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

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

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

  • @dkosmari
    @dkosmari 3 ปีที่แล้ว +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.

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

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

    • @fadhilimalongo9910
      @fadhilimalongo9910 2 ปีที่แล้ว +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

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

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

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

    We need more quick tips like this. Thanks so much

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

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

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

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

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

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

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

      ​@@scidja8567nah just Google stuff

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

    i l;ove u jeff

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

    Absolutely love the conciseness

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

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

  • @TobiSGD
    @TobiSGD ปีที่แล้ว +37

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

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

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

    • @fbarnea
      @fbarnea 9 หลายเดือนก่อน

      ​@@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 9 หลายเดือนก่อน +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 9 หลายเดือนก่อน

      @@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 9 หลายเดือนก่อน +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.

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

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

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

    My guy basically created Result type.

  • @arthurbm32
    @arthurbm32 4 หลายเดือนก่อน

    That's why Tanstack query is so valuable in JavaScript

  • @code4chaosmobile
    @code4chaosmobile 3 ปีที่แล้ว +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 :'(

  • @dkaraush
    @dkaraush 3 ปีที่แล้ว +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 3 ปีที่แล้ว +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.

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

    my second monitor:
    this video
    my first monitor:
    try {
    csvUrl = convertWixURL(csvUrl);
    } catch(err) {
    throw `Error converting url "${url}": ${err}`;
    }
    let req;
    try {
    req = await fetch(url);
    } catch(err) {
    throw `Error fetching url "${url}": ${err}`;
    }
    let txt;
    try {
    txt = await req.text();
    } catch(err) {
    throw `Error parsing text from url "${url}": ${err}`;
    }
    let jsonData;
    try {
    jsonData = JSON.stringify(csvToJson(txt));
    } catch(err) {
    throw `Error parsing JSON data from csv: ${err}`;
    }

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

    You just changed my life

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

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

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

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

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

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

  • @IamPali2024
    @IamPali2024 5 หลายเดือนก่อน

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

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

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

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

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

    • @temoncher
      @temoncher 3 ปีที่แล้ว +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 3 ปีที่แล้ว +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 ปีที่แล้ว

      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 ปีที่แล้ว +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.

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

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

  • @philfreshman
    @philfreshman 3 หลายเดือนก่อน

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

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

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

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

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

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

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

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

      @@NightstalkerKK put a catch inside pipe. Done

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

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

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

      @@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 3 ปีที่แล้ว +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

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

    React hooks for async await. This is next level

  • @vader567
    @vader567 16 วันที่ผ่านมา

    Love how the core just says “welcome” 😂💀

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

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

    • @vincent-thomas
      @vincent-thomas 2 ปีที่แล้ว +2

      No, react hooks has the same format, kinda

    • @jpratt8676
      @jpratt8676 ปีที่แล้ว +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.

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

    Me, who uses Rust: ?

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

      rust ftw, just slap a ? on that bad boy

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

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

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

    Thank you for reinventing GO

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

    I love the end of this video!!

  • @maltegb
    @maltegb 3 ปีที่แล้ว +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 3 ปีที่แล้ว +19

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

    • @raenastra
      @raenastra 3 ปีที่แล้ว +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 3 ปีที่แล้ว +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 3 ปีที่แล้ว +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 3 ปีที่แล้ว +3

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

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

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

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

    We've come full circle

  • @rhysvanderwaerden5518
    @rhysvanderwaerden5518 3 ปีที่แล้ว +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.

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

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

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

    I ran into both issues. THANK YOU

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

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

  • @above-us
    @above-us 3 ปีที่แล้ว +3

    Your videos make me feel dumb. Thank you!

  • @beamer5404
    @beamer5404 3 ปีที่แล้ว +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 3 ปีที่แล้ว +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 3 ปีที่แล้ว

      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.

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

    Love these short, to the point videos!

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

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

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

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

    • @boyemarc-antoine7027
      @boyemarc-antoine7027 2 ปีที่แล้ว

      someone finally said it

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

      Because often times you want to handle errors depending on where / what occurred.

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

    Hi^ golang

  • @hannibal.b5242
    @hannibal.b5242 3 ปีที่แล้ว

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

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

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

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

    RxJS

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

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

  • @myk3_
    @myk3_ 9 หลายเดือนก่อน

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

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

    came for the 45 second clips, stayed for the cheesy puns

  • @RohitKumar-xs3wh
    @RohitKumar-xs3wh 3 ปีที่แล้ว +5

    first

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

      Gold 🥇

    • @RohitKumar-xs3wh
      @RohitKumar-xs3wh 3 ปีที่แล้ว

      @@Fireship 0:18 yep! this is what i do

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

    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];
    }
    }

  • @KangoV
    @KangoV 3 หลายเดือนก่อน

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

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

    Trust me, I felt that.

  • @fredhair
    @fredhair 3 ปีที่แล้ว +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.

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

    this could easily be the most useful tik tok channel for programmers

  • @toesi-chan
    @toesi-chan ปีที่แล้ว +1

    Almost starts to look like elixir error handling

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

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

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

    This was the most efficient program video I have ever witness

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

    Love content like this, keep it up Fireship ❤

  • @joshuaevans4301
    @joshuaevans4301 4 หลายเดือนก่อน

    Alternative strategy: Unify your error handling and have all the requests in a single try-catch statement

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

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

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

    Reminds me of Node-style callbacks, function (err, data)

  • @dianlabuschagne2239
    @dianlabuschagne2239 3 ปีที่แล้ว +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

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

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

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

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

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

    So much info, in so little time

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

    Man we need more tips like this ! its awesome

  • @mathematical-guy1728
    @mathematical-guy1728 ปีที่แล้ว

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

  • @julkul99
    @julkul99 9 หลายเดือนก่อน

    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.