16.13: async/await Part 1 - Topics of JavaScript/ES8

Поделиться
HTML-код
  • Опубликовано: 17 ноя 2024

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

  • @yanfoo
    @yanfoo 6 лет назад +32

    @TheCodingTrain Daniel, beware that you properly return the expected Promise! At 4:50, your async function returns NOTHING, but the code executes anyway because the function does return a Promise internally. The issue you'd have is that the delay function gets's called, but if you expect to pass down a return value from the delay function, you would've lose that value, here. Unless the behavior is documented, you should return a value inside a promise chain.
    It is also important to note that promises are also recursive (DFS)! And you can still chain a promise AFTER a catch handler.

    • @TheCodingTrain
      @TheCodingTrain  6 лет назад +5

      Should it have been: return await delay(time); ?

    • @yanfoo
      @yanfoo 6 лет назад +6

      Yes. Not returning anything may cause unexpected behaviors. For example, let's say we have
      delay(1000)
      .then(() => someAsyncFunction())
      .then(result => processResult(result))
      ;
      and we want to debug "result", a naive approach would be to insert a console.log there
      delay(1000)
      .then(() => someAsyncFunction())
      .then(result => console.log(result)) // debug
      .then(result => processResult(result))
      ;
      but this would fail because result is not returned from the debug line (i.e. console.log returns void). It's just a good habit to either forward the resolved value, or return a transformed value (as in a pipeline). Promises are about processing data asynchronously.
      As a side note, even though it is a simple case, having a delay as initial example may not be the best example for demonstrating promises :) It is always best to run synchronously unless an external process is involved, usually loading something. For example, loading an image;
      function loadImage(url) {
      return new Promise((resolve, reject) => {
      let img = new Image();
      img.onload = () => resolve(img);
      img.onerror = reject;
      img.url = url;
      });
      }
      function delay(ms) {
      // return a function with a promise
      return (value) => new Promise((resolve, resject) => {
      if (isNaN(ms) {
      reject(new TypeError('Invalid timeout : ' + ms));
      } else {
      setTimeout(() => resolve(value), ms);
      }
      });
      }
      loadImage("path/to/image.png")
      .then(animateImage) // [async] function animateImage(img) { .... return img; }
      .then(delay(1000))
      .then(fadeOutImage) // [async] function fadeOutImage(img) { .... return img; }
      ;

    • @TheCodingTrain
      @TheCodingTrain  6 лет назад +15

      Thanks for all this info, I've pinned this thread!

    • @BinaryReader
      @BinaryReader 6 лет назад +1

      you know tho, rather than using a promise chain, you could just await those cases... so rather than writing...
      delay(1000)
      .then(() => someAsyncFunction())
      .then(result => console.log(result)) // debug
      .then(result => processResult(result)) // result === undefined
      could just be rewritten as...
      await delay(1000)
      const result = await someAsyncFunction()
      console.log(result)
      await processResult(result)
      It is the exact same functionality with the subtle difference that "result" is now available in scope (no need to return it)
      this whole thing can now be wrapped up as a function like so...
      const dowork = async () => {
      await delay(1000)
      const result = await someAsyncFunction()
      console.log(result)
      return await processResult(result) // assumed to unwrap Promise
      }
      ...
      dowork().then(_ => {}).catch(_ => {})
      the thing about async/await is it pretty much mitigates the need to .then() and .catch() entirely. Promise chaining (while fine in some cases, like fetch(..).then(res =>res.json()) as a kind of map) is actually really awkward for complex control flow. The retention of variables in scope is a subtle but powerful feature that significantly removes complexity around conditional control flow. making things easier overall.

    • @yanfoo
      @yanfoo 6 лет назад +3

      Async / await is not yet available in all browsers, but Promises are (either natively or through a polyfill). Besides, I prefer having chainable .then and a .catch (or multiple .catch) instead of wrapping all the awaiting functions (i.e. promises) inside a try...catch block.
      It's not because a language offers some syntax sugar that it becomes the best solution every time.

  • @braidata
    @braidata 2 года назад +1

    The philosophical depth of those farewells where he says "see you in the next video, maybe, maybe not" is incredible.

  • @MichaelSeltenreich
    @MichaelSeltenreich 3 года назад +2

    -Await, delay, time.
    -Await...... Delay........ Time....! (pause to ponder)
    -Then I can return.
    This is one of the most philosophically deep statements I've ever heard!
    3:31

  • @Justenphelps
    @Justenphelps 4 года назад +2

    After 10+ videos on Async/Await, this is the first one to really click for me. Thanks a bunch!

  • @juliancaste3914
    @juliancaste3914 6 лет назад +5

    thank you for teaching to people who dont have money to pay a university you're helping many people like me

  • @Ranner198
    @Ranner198 6 лет назад +19

    WE'RE @ ES8 ALREADY?!?!?!?!?!?! I'm not ready xD

  • @ndukwearmstrong
    @ndukwearmstrong 5 лет назад +5

    yea, this is the best programming tutor hav met on youtube. Kip it up sir,

  • @wahibakamoulcode
    @wahibakamoulcode 6 лет назад +16

    ur not boring like other I really like your video ur helpful thanks coding train (:

  • @Caraxian
    @Caraxian 6 лет назад +10

    async/await are exactly what I have always wanted. Why didn’t I learn these earlier. Goodbye chains of 50 then

  • @omegapirat8623
    @omegapirat8623 5 лет назад +1

    I like your clear pronunciation.

  • @flanderstruck3751
    @flanderstruck3751 2 года назад

    So many likes in every async await tutorial. So many people understanding; I feel totally left out

  • @offtheball87
    @offtheball87 6 лет назад +1

    You were right, this does seem a lot nicer to me :)

  • @grainfrizz
    @grainfrizz 6 лет назад +2

    Love this episode, Dan!

  • @mzamomahaeng268
    @mzamomahaeng268 3 года назад

    love the passion man. thank you

  • @kustomweb
    @kustomweb 6 лет назад

    I like this a lot more than a bunch of thens.

  • @ianchui
    @ianchui 6 лет назад +2

    I love coding train

  • @BloodyScythe666
    @BloodyScythe666 6 лет назад

    didn't quite understand async/await by that video. I think the example video will clarify things and I'll hopefully be able to understand then.

    • @TheCodingTrain
      @TheCodingTrain  6 лет назад +2

      Yes, try part 2 (linked in video description and let me know!)

  • @ZombieBrainz
    @ZombieBrainz 6 лет назад +1

    I find it ironic that the modifier is "async" when what it effectively does is causes promises to operate synchronously... i.e. blocking. Or maybe I'm failing to understand. Keep up the great work!

    • @TheCodingTrain
      @TheCodingTrain  6 лет назад +1

      The blocking only happens inside the async function itself! But when you call the async function it happens asynchronously! (if that makes sense)

  • @soufianta8374
    @soufianta8374 Год назад

    Hi. A dumb question probably, how does js deals with different return values from different blocks (if, for, function) returns ?? Does the function not stops execution when it encounters a return statement ? Thanks

  • @saikhantkyaw8714
    @saikhantkyaw8714 4 года назад

    Best teacher

  • @MasterPedroke
    @MasterPedroke 6 лет назад +9

    You should be more confident about your work, your videos are awesome!

  • @Jason-ru7xt
    @Jason-ru7xt 3 года назад

    is async and await the same as the ordinary callback function ?

  • @lookalike6270
    @lookalike6270 5 лет назад

    How many active timers can a Javascript program have? What if you need more than one? Btw- your tutorials are excellent!

  • @waelchiha6489
    @waelchiha6489 6 лет назад

    really nice way to teach

  • @nomangulkhan
    @nomangulkhan 6 лет назад +2

    Amazing brother!

  • @rishin4829
    @rishin4829 3 года назад

    You are my hero

  • @FancyLillyChaan
    @FancyLillyChaan 6 лет назад +2

    I think You are such an amazing person :)

  • @rob10eSF
    @rob10eSF 6 лет назад +5

    How about this:
    async delayES8(time) {
    try {
    await delay(time);
    createP('hello');
    } catch (err) {
    console.error(err);
    }
    }
    Embed your .then, .catch into the async function.

  • @d14nc4r0
    @d14nc4r0 6 лет назад

    Too short! hehehehe
    Nice video, I really like the didactic way in which you explain things :)

  • @Kartofkaable
    @Kartofkaable 5 лет назад

    Thank you! Very useful!

  • @shadowalker101
    @shadowalker101 6 лет назад +3

    Crikey, not sure whether I should spend the time learning promises or just move straight onto async/await =0

    • @Caraxian
      @Caraxian 6 лет назад

      shadowalker101 depends on what you want to work with. In real world web applications using async/await won’t be a great idea because older browsers will hate it, but if you’re just doing it for yourself you could go either way

    • @nahueljo
      @nahueljo 6 лет назад +1

      Well they're sort of part of the same thing.

  • @DOM-cc
    @DOM-cc 6 лет назад

    Thx man, you helped a lot!

    • @DOM-cc
      @DOM-cc 6 лет назад

      no, got that fail again ._. i made it the same but just with my promise function(axios post) but i only got (Promise { }) back, console.log before returning val works

  • @jl-dq5ch
    @jl-dq5ch 5 лет назад

    I love how he gives up on his example and tells you to just skip this video not even halfway through the video XD

  • @melihcelik9797
    @melihcelik9797 5 лет назад

    I don't get how this works. DelayES8 function returns nothing, how can you call a function on it? Does await returns it behind the scenes?

    • @Любомир-б9м
      @Любомир-б9м 4 года назад

      The word “async” before a function means one simple thing: a function always returns a promise. Other values are wrapped in a resolved promise automatically.
      javascript.info/async-await

  • @mariuskuehnast
    @mariuskuehnast 6 лет назад

    Please do a tetris coding challenge.

  • @sergio2212
    @sergio2212 6 лет назад

    How can I "await" an Observable?

  • @szymonxd6465
    @szymonxd6465 6 лет назад

    Where you coding?

  • @alajlan2012
    @alajlan2012 6 лет назад

    so its looks like Exception ??

  • @ac2italy
    @ac2italy 6 лет назад

    personally i prefer async() module

  • @dfdfdgggjhjjh5081
    @dfdfdgggjhjjh5081 5 лет назад

    "you can't just use 'await' anywhere in your code".... of course javascript wouldn't allow something to be that easy.

  • @winnerchen4478
    @winnerchen4478 4 года назад

    Good

  • @jeffreysmith7473
    @jeffreysmith7473 3 года назад

    I don't understand why you are making videos about subjects you don't fully understand yourself yet.

    • @Carrymejane
      @Carrymejane Месяц назад

      He exactly understand that

  • @ashtonmiddlefield9819
    @ashtonmiddlefield9819 4 года назад

    More drama than coding.

  • @toogiitube
    @toogiitube 2 года назад

    137 137th view

  • @FancyLillyChaan
    @FancyLillyChaan 6 лет назад

  • @nadavw3
    @nadavw3 6 лет назад

    You gave such a bad example.
    You missed all the benefits of async/await

    • @TheCodingTrain
      @TheCodingTrain  6 лет назад +2

      I agree this one isn’t such a good example. Did you watch the next one linked in description? I think it’s a bit better?