Why does JavaScript's fetch make me wait TWICE?

Поделиться
HTML-код
  • Опубликовано: 20 сен 2024
  • Hey, here's all the code:
    tomontheintern...
    github.com/tom...

Комментарии • 178

  • @mjdev-i1p
    @mjdev-i1p 2 дня назад +197

    dude is doing the lords work fighting against JS-Terminators

  • @theyayaa
    @theyayaa День назад +229

    Before you attack this man, please, AWAIT...he is a good man

    • @abdelrahmanhafez990
      @abdelrahmanhafez990 День назад +9

      I can tell he's a good man almost right away, but I needed to await to see what his content looks like.

    • @d.156
      @d.156 День назад +10

      .then(() => "I agree")

    • @antonpieper
      @antonpieper 21 час назад

      @@theyayaa nah, I had to Text decode his stream

    • @ArturDani
      @ArturDani 18 часов назад

      not just once but twice, AWAIT... AWAIT...

    • @r-i-ch
      @r-i-ch 16 часов назад +6

      Do you Promise?

  • @TheBswan
    @TheBswan День назад +66

    This is great. Love the node server with no framework, and the UI with code snippets during demo. Learned two new things (headers arrive before body + how simple streaming responses can be) in 6 minutes. Really nice job here, thank you!

    • @tomontheinternet
      @tomontheinternet  14 часов назад +4

      Glad you like that. I really enjoy how much you can do without pulling in libraries, especially for demonstration apps.

    • @thomasle100
      @thomasle100 9 часов назад +1

      ​@@tomontheinternetI agree! And we can do a lot with vanilla js in the frontend without frameworks :)

  • @blarvinius
    @blarvinius День назад +32

    I love this kind of DETAILED explanation ❤

  • @UliTroyo
    @UliTroyo 2 дня назад +16

    Dang, what an illustrative demo.

  • @charithaJayabahu
    @charithaJayabahu 11 часов назад +2

    Bro went deep but explained everything crystal clearly. Hope you make more videos like this. Hats off.

  • @69k_gold
    @69k_gold День назад +15

    This actually opens way to a super cool optimization. If the status code is not 2XX, there's a chance some APIs return an entire web page (like Microsoft Azure with 503 errors) waiting to retrieve that entire self-sufficient HTML document is such a waste of time. Rather, you can then flush it out and carry on with your other tasks

  • @danielghirasim2544
    @danielghirasim2544 День назад +10

    Very cool explanation, thank you! I am also getting attacked by killer robots when I code

  • @appwala3728
    @appwala3728 День назад +9

    This is great we need more depp knowledge like this. It's a request form you sir.

  • @user-qj4rr1rm8i
    @user-qj4rr1rm8i 9 часов назад

    '텀' wasn't just a designed logo, it was intended Hangul.. That's lovely.
    And this video was helpful for me. Thanks 텀.

  • @Ligma_Shlong
    @Ligma_Shlong 17 часов назад +32

    tldw the first await just waits for headers, then the second waits for the body, because its parsing a response stream (bytes come in incrementally) not the entire payload at once

    • @tomontheinternet
      @tomontheinternet  15 часов назад +14

      That’s right Ligma Schlong!

    • @sulaimanshabbir
      @sulaimanshabbir 8 часов назад +1

      ❤❤

    • @waldolemmer
      @waldolemmer 5 часов назад +3

      Thanks, Ligma Shlong. It's what I suspected, but the HTTP hint at the start threw me off

    • @rakha8812
      @rakha8812 4 часа назад +3

      Thank you Ligma Shlong!

    • @meyegui
      @meyegui 4 часа назад +3

      Ligma Shlong da real MVP

  • @pranksterboss139
    @pranksterboss139 День назад +3

    Definitely didn't know this before watching this video, I just accepted that awaiting JSON is what you had to do. Nice video!

  • @LearnWebCode
    @LearnWebCode 12 минут назад

    You're an amazing teacher; thanks for the great explanation and focusing on the "why" behind things.

  • @a_maxed_out_handle_of_30_chars
    @a_maxed_out_handle_of_30_chars 2 дня назад +12

    simple and to the point, thank you :)

  • @douglasgabriel99
    @douglasgabriel99 21 час назад +2

    Already knew that, but the way this video explained was so entertaining! Really great work!

  • @ThisAintMyGithub
    @ThisAintMyGithub 22 часа назад +1

    Wow, I had no idea and I've been using Node for 5 years. Great video!

  • @paperC_CSGO
    @paperC_CSGO 5 часов назад

    Really like videos like this, going into detail on specific, small things in web development. So many other videos out there are general overview courses, but for us junior devs these type of videos are gold to expand are knowledge

  • @ApplyIT2021
    @ApplyIT2021 15 часов назад +1

    Practical explanation is really amazing...

  • @antonpieper
    @antonpieper День назад +3

    I didn't know xou could create a textdecoder and read the stream, very cool. I would have probably used SSE before this video

  • @MAK_007
    @MAK_007 8 часов назад

    love these type of videos with showcasing practically. thanks for the video. great work

  • @hackytech7494
    @hackytech7494 13 часов назад

    Thank you very much this video, learned a lot, I was constantly being disturbed by the thought that why do I have to do the await two time, but now I know. Thanks to you

  • @dog7908
    @dog7908 5 часов назад

    waaaait a second! it's 텀! wow. I'm surprised as a Korean. I thought I saw illusion, so I had to rewind and play it again. LOL nice to meet you 텀

  • @iulikdev
    @iulikdev 21 час назад

    You explained very well. Nice. Long time ago i had hard time to understand this.

  • @N_N_N
    @N_N_N 22 минуты назад

    Short and to the point, great video.

  • @tomaspecl1082
    @tomaspecl1082 16 часов назад +2

    I dont use javascript but I was using one rust library that has basically the same structure of awaiting twice. I did not understand why it did that, I could only think that they made the decoding asynchronous but that would be so weird. Now I think I know why they did the same thing.

  • @pixiedev
    @pixiedev 19 часов назад

    I haven't thought about that. nice man simple clear crisp details 👌

  • @ugotworms
    @ugotworms 3 часа назад

    ...just finished watching Lost, cool to see John Locke is coding now! Seriously though, good explanation, I never gave thought to why I had to await the `.json()` call, just figured it was some backwards-compatibility quirk..

  • @PooyaBadiee
    @PooyaBadiee День назад

    Thank you so much, I did not know you can listen into body stream.
    Great video

  • @tiltMOD
    @tiltMOD 7 часов назад

    This is beyond informative! Thank you!

  • @eyenfernandotuyon5075
    @eyenfernandotuyon5075 10 часов назад +1

    XD the end of the video when it cuts exactly when is talking about the quality... makes me laught as fk

  • @solomanter
    @solomanter День назад

    Perfect explanation, Thanks a lot!

  • @antoinelb8509
    @antoinelb8509 День назад +6

    So why there is not second await on axios? (maybe both are combined?)

    • @JagaSantagostino
      @JagaSantagostino 18 часов назад +3

      Axios doesn’t use fetch internally, it predates fetch even existing by a few year, it is based on XMLHttpRequest

  • @aamiramin6112
    @aamiramin6112 19 часов назад

    Thank you so much for sharing this learned something new.

  • @colorfulmoth
    @colorfulmoth 22 часа назад

    thank you kind sir for this byte sized knowledge stream

  • @jaomuro
    @jaomuro 18 часов назад

    realy nice content, very good example for something that i just had a concept about, now i'm a subscriber

  • @purdysanchez
    @purdysanchez 12 часов назад

    I'm not gonna watch this video, but it's probably because one await is to see if/when the endpoint responds and the other await is for the response to finish.

  • @o11k
    @o11k 14 часов назад

    Great explanation, thank you

  • @foraminifera7001
    @foraminifera7001 8 часов назад +1

    What is this theme of your terminal? I really like it) Is this something like OhMyPosh or Neovim theme?

  • @webjohn
    @webjohn 6 часов назад

    Really great video but the last 5 seconds got me subscribed

  • @dennischen2922
    @dennischen2922 День назад +3

    Your Neovim setup looks gorgeous, could you share your dot files?

    • @tomontheinternet
      @tomontheinternet  13 часов назад

      github.com/tom-on-the-internet/dotfiles
      Enjoy!

  • @demmidemmi
    @demmidemmi День назад +2

    While your video is correct in all the technical aspects it does not in anyway answer the question proposed. Maybe your point was to discuss other subjects tangent to the original question and that's valid.
    But the real reason it's split into two awaits is because it allows you to split up the work or ignore the body if it's not needed this gives more flexibility and possible optimizations it has direct connection with the size of the body or the headers.

    • @thesquee1838
      @thesquee1838 День назад

      I mean he does answer the question though. What you are answering is why the functions were potentially designed the way that they were. The answer to "why do we need to await response.json()" is simply because it converts the body to json, and the body of the http request may not be ready yet when the promise from fetch() resolves. The answer to "why were the apis designed this way" is what you said, as it gives more flexibility and possibility for optimizations.

    • @demmidemmi
      @demmidemmi День назад

      @@thesquee1838 his question is why are they two. To answer that you need to look into what are the differences between having one or two awaits. A short header and longer body can absolutely be handled in one await and it is in plenty of implementation so his answer does not in any way answer the original question even though it's an excellent look at long response times.

  • @nameless5724
    @nameless5724 22 часа назад +3

    Wow You gained a new subscriber

  • @dontignore5567
    @dontignore5567 23 часа назад

    That was very informative, thank you

  • @dasten123
    @dasten123 9 часов назад

    Learned something. I always thought the first fetch was resolved as soon as the connection is established. Didn't now it resolves when the headers have arrived

  • @bartlomiejuminski
    @bartlomiejuminski 20 часов назад

    Quality video, thanks :)

  • @nicholas_obert
    @nicholas_obert 10 часов назад

    How does JS know when the async for loop is finished? Does it check whether the "body" property is bound to a promise? Or maybe the "body" property is a Promise type and it gets converted into a blob type (or whatever JS type that is) only after it has been awaited so that typeof(response.body) is a promise and typeof(await response.body) is the actual body?

  • @poorlytaught8060
    @poorlytaught8060 10 часов назад

    I actually liked the music tbh

  • @Anythiny
    @Anythiny 23 часа назад

    Keep posting more such stuff

  • @danielgilleland8611
    @danielgilleland8611 18 часов назад +1

    ... which begs the question, what if all you want is the Header information? Can you then send a cancellation token after getting the response so that the server can dispense with continuing its response of the body?

  • @ashish_prajapati_tr
    @ashish_prajapati_tr День назад

    I get it now. Great explanation

  • @LcyYoutube
    @LcyYoutube 20 часов назад

    Interesting video, thanks!

  • @MontaGao
    @MontaGao 2 дня назад +1

    really dig ur nvim conifg

  • @andrewcraig8177
    @andrewcraig8177 11 часов назад +2

    This is also why the fetch request usually needs to be wrapped in a try/catch. If the server responds with a 4XX instead of a 2XX code, there will be no json for the .json() method to parse on the response and your app will crash.

  • @phillipnguyen3094
    @phillipnguyen3094 10 часов назад

    This video is awesome. I'm learning new things. One more subscribe for you.

  • @monstercameron
    @monstercameron 16 часов назад

    thanks for the lesson!

  • @joselazovargas
    @joselazovargas 6 часов назад

    So well explained

  • @Mazzphysics
    @Mazzphysics 22 часа назад

    I learned stuff today!

  • @CrazyWinner357
    @CrazyWinner357 День назад +3

    But why doesn't fetch wait for body? What does it accomplish with this way

    • @casper64
      @casper64 23 часа назад +2

      It’s in the video my programmer

    • @quangvanduy1151
      @quangvanduy1151 23 часа назад +1

      it's the design choice to make decisions based on the returned status code or header content immediately, sometimes you might wanna use that info before deciding to json() it

    • @СергейМакеев-ж2н
      @СергейМакеев-ж2н 21 час назад +4

      One of the obvious reasons is that the body could be a file larger than your entire RAM, so it wants you to get the headers (including Content-Length) and make a decision: do you want to download it in one go, using one of the "easy" functions like .bytes() or .json(), or would you rather download it piece by piece, using a ReadableStream object.

    • @samuelwaller4924
      @samuelwaller4924 9 часов назад

      ​@@СергейМакеев-ж2н it's JS, i think we already know the answer

  • @glebbash
    @glebbash 20 часов назад

    What do you use for recording? Quite cool that you can drag the webcam window during recording.

    • @tomontheinternet
      @tomontheinternet  13 часов назад

      I’m using Cleanshot X on Mac. It’s a great program.

  • @hasil3d
    @hasil3d 7 часов назад

    Doesn't that make response read unatomic? You're supposed to read the whole response as a whole thing or not read at all, but here it seems that there is a possibility of reading the headers and failing to read the rest of the body.

  • @saiyijinprince
    @saiyijinprince 8 часов назад

    Then my next question is why does the fetch returns with headers and not just wait until the response is ready?

  • @AmodeusR
    @AmodeusR 14 часов назад

    If I could guess I wouldn't be watching this video 👁👄👁

  • @raulandj
    @raulandj 7 часов назад

    i was literally thinking about this today 🤣

  • @heyiammahadev
    @heyiammahadev 4 часа назад

    Is there a chance that server sends 200 first but something happened while sending body and server error or bad request occurs

  • @triputrafauzanhradji8005
    @triputrafauzanhradji8005 Час назад

    Never knew for await is a thing in JS

  • @eldrago4321
    @eldrago4321 13 часов назад +2

    I think it was not correct in my opinion
    First await (await fetch()):
    You get a Response object with:
    Headers: Accessible via res1.headers.
    Status Code: Accessible via res1.status.
    Body (in raw form): Not yet directly accessible.
    Second await (await res1.json()):
    You parse the body (which is likely in JSON format).
    This returns the actual data (in the form of a JavaScript object or array).
    So, with Axios:
    One await (or .then()) is enough to access both the headers and the parsed body (JSON data).
    You don’t need a second await or additional parsing step like res.json().

  • @iamrajthomas
    @iamrajthomas 6 часов назад

    Pretty Neat. Good one. 🎉

  • @t1m3__
    @t1m3__ День назад

    Great video!

  • @DemiGoodUA
    @DemiGoodUA 20 часов назад

    Always wondered why there is no asynchronous JSON.parse. If we need to parse a very large JSON, our application will hang

    • @tomontheinternet
      @tomontheinternet  13 часов назад

      I think the parsing has to take place on the main thread. I’m sure there are optimizations the browser could do though

  • @dalekman8945
    @dalekman8945 18 часов назад

    Video cut off right at the end during the call to action.
    Other than that great vid!

  • @Dopamine432
    @Dopamine432 8 часов назад

    what terminal are you using. it looks super cool

  • @duechilidance5388
    @duechilidance5388 20 часов назад

    great video, subscribed

  • @VerySadBatman
    @VerySadBatman 6 часов назад

    Worth a sub!

  • @thydevdom
    @thydevdom 17 часов назад

    Always wondered how that worked.

  • @digital39999
    @digital39999 День назад

    But I wonder why doesn't fetch, like fetch the whole response along with data and everything, and still why does json need await, does fetch like return headers and then on sync function collect data and json promise resolves once data is done?

    • @fltfathin
      @fltfathin День назад

      Fetch does fetch the response, just not eager loading/ instantiate the object right away. Deserializing need compute time. Also, failing to get the response and failing to deserialize it should be handled separately

  • @ayushKumar-9835
    @ayushKumar-9835 7 часов назад +1

    Ok, I was checking out that chat GPT uses post request instead of a web socket but I was wondering that how they are able to send the data character by character.
    I think this explains how.

  • @sealuke2724
    @sealuke2724 13 часов назад

    nice insight

  • @von-fur-wegen-gegenolli9196
    @von-fur-wegen-gegenolli9196 День назад

    Very interesting! 👍

  •  День назад

    Great vid man

  • @mahabubul-hasan
    @mahabubul-hasan День назад +2

    what font is that in your editor?

  • @timber2lease
    @timber2lease День назад

    what happens if the response is cancelled before completing? would it still be a 200?

    • @pedropertino7324
      @pedropertino7324 17 часов назад

      yes, but the promise for json/blob/text would be rejected with some error

  • @satpaingthu4124
    @satpaingthu4124 4 часа назад

    Let him end his sentence.. please 😭😭

  • @atrus3823
    @atrus3823 День назад

    I’m guessing fetch continues to get the body whether json has been called or not? Or does it wait for a call to json to get the body? It strikes me waiting would be risky since the connection could be lost, and also inefficient.

    • @pedropertino7324
      @pedropertino7324 17 часов назад

      is not up to fetch really, the operative system is the one handling the tcp connection, if the user app stops reading from the socket, the os will stop acking the other end, but some amount will be buffered whether you like it or not (is its a small request, most likely all of it)

  • @Manish___Choudhary
    @Manish___Choudhary День назад +4

    Can we use this ?
    await fetch("/json").then(res=>res.json())

    • @thijsyo
      @thijsyo День назад +4

      Yes, functionally that is the same thing

    • @darkee03
      @darkee03 День назад +2

      Those are kinda two awaits with only one await keyword, same-same

  • @MySisterIsASlytherin
    @MySisterIsASlytherin 25 минут назад

    very cool!

  • @mscholzdev
    @mscholzdev 2 дня назад

    Thanks

  • @maverickchan9552
    @maverickchan9552 5 часов назад

    second approach is like SWIFT doing a async api call. and streaming data is nice, like a real chat app

  • @asdfasdfuhf
    @asdfasdfuhf 4 часа назад

    I dont get it, so why would you want to do it the stream way? What's the pro?

  • @HudsonPereiradishark
    @HudsonPereiradishark Час назад

    nice content, ty

  • @praveenvinopv9929
    @praveenvinopv9929 12 часов назад

    You earned a subscriber ❤️

  • @malakggh
    @malakggh 18 часов назад +44

    Great video, put please get rid of this annoying background music!!

    • @tomontheinternet
      @tomontheinternet  13 часов назад +7

      Yeah, maybe the music is annoying.
      People reading this comment, please let me know.
      Should I have music?
      Why?
      Thanks!

    • @jhehn3
      @jhehn3 13 часов назад +10

      @@tomontheinternet Honestly I like the music

    • @hackytech7494
      @hackytech7494 13 часов назад +13

      @@tomontheinternet Which music we are talking about ? 😅 I was so focused on content that I didn't hear it.

    • @tusmuertos2667
      @tusmuertos2667 13 часов назад +7

      @@tomontheinternet I realized that there was music when I read the comment

    • @diegoalvarez437
      @diegoalvarez437 13 часов назад +4

      @@tomontheinternet That's probably because most of us are playing our music and this mixes with the one you put on. Also there's a lot of people who dislike instrumental music. I personally like it.

  • @dannyisrael
    @dannyisrael 22 часа назад

    Love it

  • @sifatulrabbi
    @sifatulrabbi 23 часа назад

    love the video

  • @cm3462
    @cm3462 16 часов назад

    background music is so nice
    first time here

  • @Kaviarasu_NS
    @Kaviarasu_NS 5 часов назад

    ❤️‍🔥❤️‍🔥

  • @cooltrashgamer
    @cooltrashgamer 10 часов назад

    Why was the ending so abrupt, hahaha

  • @slackergeek2007
    @slackergeek2007 12 часов назад

    Useful info. However your video ended mid-sentence

  • @carlossn9511
    @carlossn9511 День назад

    the ending!! LOLLLLL

  • @user-q7m4z
    @user-q7m4z 9 часов назад

    Can I find this theme for VSCode?

  • @taru15
    @taru15 2 часа назад

    What is the name of the font you use sir ?