Async JavaScript with Promises

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

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

  • @hraynaud
    @hraynaud 9 лет назад +2

    Thanks Kyle. I've been struggling to grok promises for a while now and of all of the specs, blogs, and conference talks your simple 12 minute video was by far the clearest. Well done.

    • @kylerobinsonyoung
      @kylerobinsonyoung  9 лет назад

      +Herby Raynaud Awesome! So glad to hear! Thank you! :D

  • @jeremiahscanlon
    @jeremiahscanlon 7 лет назад

    I've been fumbling around with converting my callback functions to promises forever, but I finally understood how to make it work after watching this video. Thanks!

  • @SarbbottamBandyopadhyay
    @SarbbottamBandyopadhyay 9 лет назад +5

    This is the best explained tutorial/video on JavaScript Promise that I have watched so far. Thank you.

    • @kylerobinsonyoung
      @kylerobinsonyoung  9 лет назад

      +Sarbbottam Bandyopadhyay Thanks! :D

    • @SarbbottamBandyopadhyay
      @SarbbottamBandyopadhyay 9 лет назад +1

      +Kyle Robinson Young Would love to see a follow up video, for the methods.
      * Promise.race()
      * Promise.reject()
      * Promise.resolve()

  • @TransConBrilliance
    @TransConBrilliance 7 лет назад +2

    Great video. I am often amazed how one topic can be easy to understand in one video and ridiculously complicated in another. Promises for some reason (video tutorials and website documentations) always fall into the extreme of overly complicated or straight to the point easy. Your video is easy to understand. Thank you for saving my time.

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

      I agree. This video made it sound very simple to understand.

  • @r7yz
    @r7yz 9 лет назад +2

    Watched two videos before this one. Those other two didn't really help, this one made it crystal clear. The no-nonsense jumping right into the right world example was excellent. Great job man! Subbed and will be relying on your other videos for js too!

  • @brizzpatel
    @brizzpatel 9 лет назад +1

    Thattt was a 12 minutes of confidence booster session for using promises. Pretty concise still almost all we need to know about promises. Thanks Kyle :)

  • @pankajbhandari5026
    @pankajbhandari5026 9 лет назад +2

    The way it was explained, made promise quite easy to understand :) Thank you

  • @CBusschaert
    @CBusschaert 8 лет назад +2

    omg
    I understood a js video on something I didn't know anything about.
    And I played it at speed 2
    You're good!

  • @Unitazy
    @Unitazy 8 лет назад +4

    Watched like 5 times to start understanding lol! Still the best video out there!

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

      A tip: watch movies on flixzone. Been using them for watching loads of movies lately.

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

      @Cash Colby yup, I have been using flixzone} for months myself :D

  • @ahsenkh
    @ahsenkh 8 лет назад

    At 3:39, you say "after then has been called, it returns the promise itself ..."
    Does this mean the control is first shifted to `then` block (which returns a promise but does not execute its logic) and then to the next `catch` block, in case of an error throw from `fetch('bears1fds.txt');`?

  • @seewhatisee6657
    @seewhatisee6657 8 лет назад +1

    Simple with clear concept.
    Thanks for the video .

    • @aruprakshit7218
      @aruprakshit7218 8 лет назад

      Yes this kind of examples helps to understand the subject very well. +1

  • @andym870
    @andym870 8 лет назад

    HI Kyle, just noticed at minute 3:38, chaining the catch (promise.then(...).catch(...) ), shouldn't it catch the error thrown by then() (then() creates a new promise)? so to catch the error for the promise, I think promise.catch() was fine.

  • @marhawk6468
    @marhawk6468 7 лет назад +1

    Very well explained! Subscribed! Keep em coming

  • @buttermuffin3752
    @buttermuffin3752 9 лет назад

    Helped me understand promises immensely, thanks!

  • @yllimdanny
    @yllimdanny 8 лет назад +1

    Thanks kyle , what a simple and clear video... btw why i dont see any semi-colon at the end of each line... javascript no long require semi-colon to end a line like sass ??? regards

    • @kylerobinsonyoung
      @kylerobinsonyoung  8 лет назад +1

      +Danny Lim Thanks! Semicolons are optional in JavaScript. It's a common misconception they are required because there is a lot of fear spread about not using semicolons. I made a video about it: ruclips.net/video/gsfbh17Ax9I/видео.html but the gist is, try both and make your own opinion.

  • @aberba
    @aberba 9 лет назад +15

    If you were my lecturer, I would never get bored :)

  • @DmitryLapshukov
    @DmitryLapshukov 8 лет назад +1

    Thanks for video Kyle. Question, how you run CommonJS declared module (fetch.js) in Chrome?

    • @kylerobinsonyoung
      @kylerobinsonyoung  8 лет назад +1

      +Dmitry Lapshukov I'm using a tool called budo. It creates a static file server and compiled CommonJS as you request it with Browserify. I did an earlier video on getting this setup: ruclips.net/video/Ads1A7pn2LI/видео.html
      Then when ready to deploy, I use Browserify to compile to a file and publish that.

  • @billsimpson4487
    @billsimpson4487 8 лет назад +2

    Great explanation! Thank you!
    I'm now wondering how to go about looping through a series of async calls (as thought they were synchronous) and also accessing common objects on subsequent executions. Can you suggest how I might accomplish the following?
    run()
    create a list of survey XML files (paths)
    loop for each xml file found
    read and convert XML file text to JSON data (object)
    create a partial Surveyform (mongoose) doc from JSON data
    save Surveyform, retrieve new Survey._id
    create Attachment doc from JSON data
    save Attachment doc, retrieve new Attachment._id
    update Surveyform with Attachment._id (link)
    save Surveyform

    • @kylerobinsonyoung
      @kylerobinsonyoung  8 лет назад +1

      That's a very specific example request heh. Someday (or now depending on the environment you're targeting or if dont mind using a transpilier) you can use async/await: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function to execute a series of async call as if they were async.

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

    Amazing tutorial. Thanks !
    Do you have something working with Promise / Async function and Await ?
    When you have a sequence of stuff that they HAVE TO execute in a certain order. It's giving me a tough time haha

  • @junedchhipa
    @junedchhipa 8 лет назад +1

    Finally understood!!
    Thanks man, subscribed

  • @MichaelMammoliti
    @MichaelMammoliti 8 лет назад

    nice and clear.. could you please tell the font you are using? :) thanks

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

    What font is that? I need that. Specifically the very rounded parameter character

  • @bagoquarks
    @bagoquarks 8 лет назад

    In your 'fetch()' routine (approx 9:49), you 'return' the 'reject' function on lines 6 and 7. On line 8 you call the 'resolve' function. I believe the 'return' keyword should be omitted; you should just call the 'reject' function as you do the 'resolve'..

    • @kylerobinsonyoung
      @kylerobinsonyoung  8 лет назад +1

      +Michael OBrien (hardwareMike) If we omit the `return` keyword on lines 6 and 7, it would call `reject()` and then continue on to calling `resolve()` (and possibly `reject()` again). I am returning early in the function as a way to avoid having to nest if/else statements.

    • @bagoquarks
      @bagoquarks 8 лет назад

      +Kyle Robinson Young
      As Ed used to say to Johnny, "You are correct, sir!"
      I was compelled to go back to MDN, read the 'return' entry, and be humbled. The reject function passed into the promise is *evaluated* and that value is returned by 'return'. The 'resolve' has an implied return as it is the last statement in the promise function.

  • @Ganesh-ph4gm
    @Ganesh-ph4gm 9 лет назад

    +Kyle do u have benchmarks for async and promise.

  • @rexxar110991
    @rexxar110991 8 лет назад +1

    Very clear and informative, thanks !

  • @huihao8058
    @huihao8058 8 лет назад +1

    Thank you Kyle. Now it makes total sense!

  • @FranciscoValenzuela92
    @FranciscoValenzuela92 9 лет назад +1

    What is your dev enviroment set up? IDE, theme, recomended packages and so on :) thanks in advance!

    • @kylerobinsonyoung
      @kylerobinsonyoung  9 лет назад +1

      +Francisco Valenzuela I'm on OSX and use Atom editor. With the One Dark theme and Monokai syntax theme. Some of the packages I use are minimap, webbox-color, and emmet. :)

    • @FranciscoValenzuela92
      @FranciscoValenzuela92 9 лет назад +1

      Cool :) Thanks bro!

  • @softwaremountainvladzamsmo1683
    @softwaremountainvladzamsmo1683 9 лет назад

    Good video, thank you very much. The thing i didn't understand clearly:
    Point 1m34s: we see `then` and `catch` functions declarations. These functions are not receiving any parameters.
    Point 2m47s: we see we are calling `then` function and passing callback to it.
    So, what is the trick: where can we see what is passed as `bears` to the provided callback when it is invoked? Am i missing something?

    • @kylerobinsonyoung
      @kylerobinsonyoung  9 лет назад

      +Vlad Zamskoi Thanks! Hopefully I can answer your question.
      At 1m34s, I am demonstrating what a Promise object will look like. It's pseudocode to show that Promise is a simple object with 2 functions. We don't need to declare a Promise, they are already declared and live in the global scope.
      The method signatures are: `then(onFulfilled[, onRejected])` and `catch(onRejected)` or each take a callback that gets called if resolved or rejected. developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then

    • @softwaremountainvladzamsmo1683
      @softwaremountainvladzamsmo1683 9 лет назад

      Thank you for clear explanation. Provided reference is exactly what i was interesting in.

  • @glenndufresne4598
    @glenndufresne4598 8 лет назад

    In fetch(), why is it that reject is handled as "return reject(err)" and the resolve is handled with simply "resolve(body)?

    • @kylerobinsonyoung
      @kylerobinsonyoung  8 лет назад +1

      It is a way to exit the function early. It could have been wrote like this instead: reject(err); return; or we could have used an "else" statement for the rest of the function. But since the return value within that function doesn't matter, we can simplify it and return to early exit the function.

    • @glenndufresne4598
      @glenndufresne4598 8 лет назад

      Oh! I was thinking that the reject()/resolve() would exit the function. Thanks for clarifying

  • @undefined-mj6oi
    @undefined-mj6oi 7 лет назад +1

    This is really well-explained. Thank you so much!

  • @KhaledGarbaya
    @KhaledGarbaya 8 лет назад

    Good video, just one thing if the file is cached the status code will be different and you will still throw the error even though you have received the content

  • @kilobitz8639
    @kilobitz8639 8 лет назад +1

    Best example I've seen

  • @qwe123727
    @qwe123727 9 лет назад

    Kyle,
    I am getting error : Cannot find module 'xhr'
    How do I resolve this?

    • @kylerobinsonyoung
      @kylerobinsonyoung  9 лет назад

      +Ethashamuddin Mohammed It sounds like you'll need to install it. Try running `npm install` from within the project folder.

  • @zwhitchcox
    @zwhitchcox 9 лет назад

    in Promise.all, why wold it matter which promise comes in first, if it's not resolved until all are loaded?

    • @kylerobinsonyoung
      @kylerobinsonyoung  9 лет назад

      +Zane Hitchcox Just making sure to let people know Promise.all isn't sequential. I initially thought it would do Promise.all([first, second, third]) and was wrong. So I wanted to be sure to make a comment about that in case anyone else thought that as well.

    • @zwhitchcox
      @zwhitchcox 9 лет назад

      +Kyle Robinson Young Ohh ok. I thought you were saying they would come in one at a time, and then the callback would be executed for each

  • @lings628
    @lings628 7 лет назад +3

    That was very promising, thank you.

  • @vishumzn
    @vishumzn 8 лет назад +8

    Good good good, all good, subscribed!

  • @amitdubey3207
    @amitdubey3207 8 лет назад

    what about if i need the bear data in different function or use how to access the data globally

    • @kylerobinsonyoung
      @kylerobinsonyoung  8 лет назад

      One way is hoist the variable:
      var bears = []
      promise.then(function (data) {
      bears = data
      })
      // bears variable is available here but just be aware, it will be an empty array until the promise resolves some time in the future
      Or a better way, imo, is pass as an argument to the other function:
      promise.then(function (data) {
      doBearStuff(data)
      })
      function doBearStuff (bears) {
      // Now we are sure that bears is the data we want
      }

    • @amitdubey3207
      @amitdubey3207 8 лет назад

      thanks a lot

  • @ehud257
    @ehud257 8 лет назад

    Thanx !!! how would you implement $.ajax instead of xhr ?

    • @kylerobinsonyoung
      @kylerobinsonyoung  8 лет назад +1

      jQuery kind of implemented their own promises but they have compatibility issues with the current native promise spec. Such as they return multiple parameters and call their `catch` handler `fail`. So you can do $.ajax().then(success, error) with jQuery directly for promise-like behavior but since they are not compatible with real promises, I wrap it in a native promise like this: gist.github.com/shama/24654eab9f6c1ed055b6ebfe776eb10d

  • @user-kq9op7oq2c
    @user-kq9op7oq2c 7 лет назад +1

    you made it easy peasy.. thanks!!

  • @jka5660
    @jka5660 8 лет назад

    It suddenly felt so easy...
    Thanks a bunch Kyle (y)
    #YouTheMan

  • @sergeyphilippenko6533
    @sergeyphilippenko6533 7 лет назад

    Promise.all, actually, saves the order of elements inside iterator. You can check it with bunch of setTimeouts

  • @hemanthpalusa
    @hemanthpalusa 8 лет назад +1

    promise.then(function(){
    console.log("Thanks for explain , I got it :) ")
    })

  • @prithvisinh
    @prithvisinh 9 лет назад +1

    This is good and really helpful.

  • @Xopsy
    @Xopsy 8 лет назад

    I just subscribed, you have very good interesting videos. But I was looking for a problem I've had this week, and it is to resolve all the promises async, then I saw you use an array but for me it is better solution if you use an object promises like this:
    pomise.all(
    {
    val1: fetch('wahtever1'),
    val2: fetch('wahtever2')
    })then(function(values) {
    log(values.val1);
    log(values.val2);
    .....
    then it doesn't matter how it is resolved, because you have some reference for them. Otherwise, if you have to do something with their values, into in an array you have to check what promises was resolved.

  • @E6YchKa
    @E6YchKa 7 лет назад +1

    thanx. very nice explanation!

  • @rockeykotwal
    @rockeykotwal 7 лет назад

    can anyone tell what to write in fetch file?

    • @kylerobinsonyoung
      @kylerobinsonyoung  7 лет назад

      Here is the source for what I used in this video: github.com/shama/letswritecode/blob/master/async-js-with-promises/fetch.js
      There are far better implementations on npmjs.com though.

  • @DuuAlan
    @DuuAlan 8 лет назад +1

    Great video, thanks, it really helped! :D

  • @tasteink
    @tasteink 8 лет назад +1

    Great video. I do appreciate it, but Y U NO USE SEMICOLON?! =P

  • @hab1tats
    @hab1tats 9 лет назад +1

    whoa, this really helped! epic

  • @AltianoGerung
    @AltianoGerung 9 лет назад +1

    Maybe next video about Generator with Promise..?

    • @kylerobinsonyoung
      @kylerobinsonyoung  9 лет назад

      +Altiano Gerung Yep! I have some planned for generators and async/await: github.com/shama/letswritecode/issues/1

    • @AltianoGerung
      @AltianoGerung 9 лет назад

      Cool.. i'll be wainting for it.. :)

  • @deanshelton913
    @deanshelton913 8 лет назад

    promise.all DOES resolve values in a gaurenteed order. Otherwise how could you ever use the values with any certainty? Source: stackoverflow.com/questions/28066429/promise-all-order-of-resolved-values and tc39.github.io/ecma262/#sec-promise.all

    • @kylerobinsonyoung
      @kylerobinsonyoung  8 лет назад

      +dean shelton You are correct. Thanks for pointing that out. I should have been more clear stating the order in which each promise resolves may not be in order but the order in which they return will be in order. Another viewer pointed that out earlier and I've added an annotation clarifying at 7:58. Thanks!

    • @deanshelton913
      @deanshelton913 8 лет назад +1

      +Kyle Robinson Young great video. subscribed. keep em coming.

  • @l0phthammer13
    @l0phthammer13 8 лет назад +3

    @4:07 I see what you did there

  • @bengi87
    @bengi87 7 лет назад +1

    So cool ...
    Thank you

  • @DavidRunger
    @DavidRunger 9 лет назад +2

    Helpful video, thanks. :) Small error, I think. 7:53 - 8:10 you mention that the order of values passed to the "then" method returned by Promise.all is not guaranteed and depends upon the order in which the promises complete. This is not correct (which is good!, because if it were then writing code to handle that indeterminacy would be messy/impossible). The order of the values *will* correspond to the order of the promises (when using an Array, at least, to pass in the set of promises to Promise.all). This JSFiddle should illustrate what I'm saying: jsfiddle.net/shtnmyrq/1/

    • @kylerobinsonyoung
      @kylerobinsonyoung  9 лет назад +3

      David Runger Awesome thank you very much for the correction! I've added an annotation to hopefully help clear that up. I really appreciate you letting me know. Cheers!

    • @DavidRunger
      @DavidRunger 9 лет назад +1

      Kyle Robinson Young Ahh, re-watching the video I think that I might have simply misunderstood what you were saying. Maybe you weren't talking about the order of the values/responses that are passed to the thenCallback, but just stating that the 2nd fetch could complete before the 1st. Anyway, I think that the annotation makes it clearer for people who might have (mis?)interpreted what you were saying in the way that I did. Anyway, nice job with the prompt correction and thanks for even putting my name in it. ;)

  • @SoeaOu
    @SoeaOu 9 лет назад +3

    good, all good

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

    Awesome video

  • @leonardoperetti6911
    @leonardoperetti6911 8 лет назад

    You are the best!

  • @TrueRDOS
    @TrueRDOS 7 лет назад +1

    Was I the only one that caught the bear pun at 4:07?

  • @JasonCtutorials
    @JasonCtutorials 8 лет назад +1

    thanks for this!

  • @piq-dg3vz
    @piq-dg3vz 8 лет назад +1

    Cool. Subscribed