JavaScript ES6 Promises - Basic Syntax

แชร์
ฝัง
  • เผยแพร่เมื่อ 23 ก.ค. 2017
  • The fundamentals about how JavaScript ES6 Promises work and how you could use them in your code.
    This is the first in a series of videos about Promises.
    Next Promise video: • More About JavaScript ...

ความคิดเห็น • 88

  • @colonelvector
    @colonelvector 4 ปีที่แล้ว +15

    Thank you, by far the best and most clear explanation of promises

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

    Wow, what a great tutorial regarding promises. Thank you, mate.

  • @joebuono8793
    @joebuono8793 4 ปีที่แล้ว +6

    Thank you, Steve. Once again, your clear and thoughtful explanations have helped me to understand a concept that I was having trouble with. As a beginner to programming, I'm grateful to have found your channel.

  • @rumbly438b7
    @rumbly438b7 6 ปีที่แล้ว +13

    Thanks. Great content . Clearest explanation on promises I've seen so far.

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

    Absolutely the CLEAREST explanation on how JavaScript Promises work from all the videos I have watched so far on that topic. I have said it repeatedly - the value of a "good teacher" is PRICELESS !!!!!!!!! Thank you Steve !

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

    Thank you very much, I have avoided to learn Promises for some years because its difficulty, but your explanation makes me confident now that I do become to love the subject.

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

    Dude. I don't know what exactly it is, but something in this video made it click. I've been using (copying) promises for so long and just hoping they would work, but now I get it. Half way through this video I opened up a replit file and played around with resolving/rejecting a promise using a random number generator, and it JUST MAKES SENSE SUDDENLY.
    Thank you so much. I'm going to have to credit you with my being able to pass the class I'm in.

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

    Thanks, Steve. I have been trying to understand promises for some time now. Your vid is by far the best explanation and I think that I finally understand how promises work. Thank you. You've got a new subscriber.

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

    This is by far the best explanation of promise I have ever seen. Thank you Steve for such an amazing content

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

    Really appreciate you. I find these videos better than any course I've purchased so far.

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

    Thank you very much! It's really helpful and friendly to beginner~❤and how lucky I found this channel !

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

    Amazing tutorial for Beginners, exceptional!

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

    This was such a clear explanation! Thank you Mr.!

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

    The explanation is so simplified that newbie would grab it once.Thank you YOU ARE AMAZING

  • @marie-elizeventer7080
    @marie-elizeventer7080 2 ปีที่แล้ว

    Thank you for a great tutorial Steve.

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

    This channel is something else, thanks a lot.

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

    Really very clear and informative tutorial as usual. I'm learning a lot with you, about javascript and CSS. Thank you so much.

  • @ianrust3785
    @ianrust3785 4 ปีที่แล้ว

    Thanks, best explanation I've found and I've looked in quite a few places.

  • @k.t.1594
    @k.t.1594 3 ปีที่แล้ว

    Best video on promises on the web. Thanks

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

    thank you! i improved my skills a lot with this explanation. :)

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

    You are favourte tech youtuber Steve . I connect so much with your explanations .Thank You !

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

    you are always my best reference, thank you

  • @kamaboko1
    @kamaboko1 6 ปีที่แล้ว +5

    I'm reminded of a line from Spinal Tap (though I'll replace "black" with "clear"): "It's like, how much more clear could this be? and the answer is none. None more clear."

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

    This is gold.

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

    Very useful video, thank you ✌️

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

    amazing man

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

    GREAT EXPLAINATION

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

    Awesome video

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

    Well explained

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

    best teacher

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

    Many thanks for the easily understadable explanation. One thing I really like about you is your voice, they're so soft I don't know how to explain but good to hear that. Have you ever thought producing a completed JS course and push it on Udemy?

  • @CesarJuarezVargas
    @CesarJuarezVargas 6 ปีที่แล้ว

    What would be the key difference between using Promises to do remote fetching v. using if / then? Can if/then be used to retrieve things from a remote computer?

    • @SteveGriffith-Prof3ssorSt3v3
      @SteveGriffith-Prof3ssorSt3v3  6 ปีที่แล้ว +1

      Cesar Juarez-Vargas if else has nothing to do with fetching remote data with ajax.
      Fetch is the new way.
      New XMLHttpRequest is the old alternate way.

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

    I think the best way to understand how Promises work in JS is to understand the Event Loop and how (micro event queue, event queue, memory heap, call stack and browser API) fit in the picture.

    • @SteveGriffith-Prof3ssorSt3v3
      @SteveGriffith-Prof3ssorSt3v3  ปีที่แล้ว

      That's understanding the bigger picture more at an intermediate level if you are talking about the event loop and the difference between tasks and microtasks plus execution content. Beginners can understand and use Promises quite effectively without having the full picture of all that.

  • @CesarJuarezVargas
    @CesarJuarezVargas 6 ปีที่แล้ว

    Line 24: is it the same "x" as in line 16? are you substituting the original value? Could you have used "y" on line 24?

    • @SteveGriffith-Prof3ssorSt3v3
      @SteveGriffith-Prof3ssorSt3v3  6 ปีที่แล้ว

      ex is a local variable inside the then function. it will contain whatever value is passed to that function. You can call the variable anything you want.

  • @rickyu1978
    @rickyu1978 6 ปีที่แล้ว

    Do all the subsequent thens need the return statement if they want to pass a value to the next then? If you are passing in req,res using a arrow function wont it look up the chain to find the nearest res? Also is it correct to say that resolve must always be in the initial aysync call, and you cant have further resolves down the chain?

    • @SteveGriffith-Prof3ssorSt3v3
      @SteveGriffith-Prof3ssorSt3v3  6 ปีที่แล้ว +1

      Correct. Each then( ) method has a function. Its return value gets passed to the next then( ) function.
      Every Promise has two possible results - success or failure. When you create a promise you give it two functions. One to call for success and one to call for failure. If you want you can add an additional Promise inside the then method as the return value.

    • @rickyu1978
      @rickyu1978 6 ปีที่แล้ว

      Great. It would be awesome if you could touch on promise.all.. Im using axios so trying to figure out axios.all and trying to pass a value between each. For Example to upload a file, the first promise would be to Obtain Authorization, Second would be to upload the file -- and all this needs to be done on the backend nodejs express server, instead of front end. -- Do you have a tut touching the above topics? Keep up the good work!

    • @SteveGriffith-Prof3ssorSt3v3
      @SteveGriffith-Prof3ssorSt3v3  6 ปีที่แล้ว

      I have a playlist on Promises where I cover .all and .race and other aspects of Promises.
      th-cam.com/video/SmPouEFKOBg/w-d-xo.html

  • @CesarJuarezVargas
    @CesarJuarezVargas 6 ปีที่แล้ว

    I tried to recreate lines 7 and 8 alone (without anything else), but got no response. multiplyTwoNumbers needs to be defined, correct?

    • @CesarJuarezVargas
      @CesarJuarezVargas 6 ปีที่แล้ว

      RECALL: Yes... I realized it needs to be defined. =)

  • @CesarJuarezVargas
    @CesarJuarezVargas 6 ปีที่แล้ว

    Would it be possible to add an if-then routine and the result be stored in a variable (for example, let x= whatever if/then routine I want) and, depending on its outcome, condition the resolve (x) or reject (x) as needed?

    • @SteveGriffith-Prof3ssorSt3v3
      @SteveGriffith-Prof3ssorSt3v3  6 ปีที่แล้ว

      Not sure exactly what you are asking. You can have if else statements inside any function. You can use if else statements to call different functions...
      if( abc === 123 ){
      f( );
      }else{
      g( );
      }
      This example calls function f( ) if the value of abc is 123. It calls the function g( ) in all other situations.

    • @CesarJuarezVargas
      @CesarJuarezVargas 6 ปีที่แล้ว

      I missed some elements on my question, sorry. Is it possible to code an if-else routine inside a Promise, store the result of the if-else routine inside a variable and, eventually, use those variables as a result/reject within the Promise?

    • @SteveGriffith-Prof3ssorSt3v3
      @SteveGriffith-Prof3ssorSt3v3  6 ปีที่แล้ว +2

      Yes. If you are building your own custom Promise (instead of a pre-built one like fetch) then you can pass whatever variables you want through the resolve( ) or reject( ) calls.
      let p = new Promise( (resolve, reject) => {
      let x = Math.random( ) * 10;
      if( x > 5 ){
      resolve(x);
      }else{
      resolve('less than 6');
      }
      }

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

    I tested with console.log (ex) return ex *2 and console.log (ex*2), with same results. Any preference on using or not the RETURN command in this case?

    • @SteveGriffith-Prof3ssorSt3v3
      @SteveGriffith-Prof3ssorSt3v3  6 ปีที่แล้ว

      I don't understand your question. Functions should have return statements, if that is what you are asking.

    • @CesarJuarezVargas
      @CesarJuarezVargas 6 ปีที่แล้ว

      Not exactly. Just for my own curiosity, I replicated your coding and, just to see what the outcome would be, I wrote line 25: console.log(ex) and then line 26 : return ex *2, and afterwards I experimented and rewrote it to this: console. log(ex*2), eliminating the next line (the one with RETURN). Both cases the result was the same. My question is, given that the result was the same is it mandatory to have the RETURN line or if the code would be considered correct with console.log(ex*2).

    • @SteveGriffith-Prof3ssorSt3v3
      @SteveGriffith-Prof3ssorSt3v3  6 ปีที่แล้ว +1

      They do two different things. console.log( ) ONLY writes something to the console. It does not provide information to anything else in your code. RETURN passes a value back from your function so it can be used.
      when you have a Promise then you are basically creating a chain of asynchronous functions. The second won't run until the first one is finished. The third one won't run until the second one is finished. To tell the second one that the first one is finished you need to use return. return will pass the value from the first function to the second one.
      let p = new Promise( ).then( ).then( ).then( )
      Inside each set of parentheses there needs to be a function.
      Inside each function there needs to be a return statement to pass the value along to the next function.

  • @MrMarkgyuro
    @MrMarkgyuro 4 ปีที่แล้ว

    in the setTimeout why did not have to apply curly braces to the resolve function?

    • @SteveGriffith-Prof3ssorSt3v3
      @SteveGriffith-Prof3ssorSt3v3  4 ปีที่แล้ว

      Because the first argument that you pass to a setTimeout call is either a function declaration or the name of the function to run. resolve is already a defined function. We just pass the name to setTimeout.

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

    So fetch has a built in promise where i can do a .then, but how does it have it built in? and why don't i have to wrap fetch in a promise? There are some other API'S that are "promissible" but how does that happen under the hood. How does one know if a API like fetch has a built in promise? thanks so much.

    • @SteveGriffith-Prof3ssorSt3v3
      @SteveGriffith-Prof3ssorSt3v3  6 ปีที่แล้ว

      The fetch( ) method returns a Promise object. That is why we add a then( ) and a catch( ) to it. If the Promise returned by calling fetch resolves .. the then( ) method gets called. If the Promise fails then the catch( ) method gets called.

    • @rickyu1978
      @rickyu1978 6 ปีที่แล้ว

      hi thanks steve, under the hood, in chrome v8 engine my guess is that the fetch api is wrapped in a promise?

    • @SteveGriffith-Prof3ssorSt3v3
      @SteveGriffith-Prof3ssorSt3v3  6 ปีที่แล้ว

      To be clear, the Fetch API is not wrapped in a Promise, it returns a Promise.

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

    Steve correct me if I'm wrong. What I want to do: I want to call fetch to get some data, and I want to assign result of fetch to some variable I declared at the start of the script, but there is no way I can safely use this variable (because of asynchronies nature of fetch as you show if I call this variable I will get undefined). So I have to work with data I get from fetch in then methods and there is no way to handle this situation differently? I ask this question because my first intention was to assign fetch to smth and use it later (for example fetch data immediately at the start of script but use data somewhere after some specific events that will happen in the future)

    • @SteveGriffith-Prof3ssorSt3v3
      @SteveGriffith-Prof3ssorSt3v3  3 ปีที่แล้ว +1

      Using promises you will want to get into the habit of creating small pure-ish functions. These functions can be called from the then( ) methods of your Promise/fetch. Whatever your small function returns will be passed to the next then( ) as the input value.
      When fetching data I will typically have a globally accessible variable or property where I store the value.
      Eg:
      const APP = {
      theData: null, //where I will store my data after it is fetched.
      init: ()=>{
      //my init function that sets up the app
      document.querySelector('#someButton').addEventListener('click', APP.getData);
      },
      getData: ()=>{
      //called from some action in your app, often a user click event.
      fetch( url )
      .then( response => {
      if( ! response.ok ) throw response.statusText;
      return response.json( );
      })
      .then( APP.processData )
      .catch(
      },
      processData: ( data )=>{
      //we can use the data object here if we want and/or save it for later
      APP.theData = data; //saved for later
      }
      }
      This playlist - th-cam.com/video/7EKebb4VUYQ/w-d-xo.html
      will tell you everything you need to know about Promises with fetch.

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

      @@SteveGriffith-Prof3ssorSt3v3 Thank you for replying! Playlist gonna be watched, guaranteed.

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

    why in case of nested thenable, when I log in console, I got little different output?

    const thenable1 = {
    then(onFulfilled, onRejected) {

    const nestedThenable = {
    then(onFulfilled) {
    onFulfilled('Future Studio')
    }
    }
    onFulfilled(nestedThenable)
    }
    };
    // convert thenable to promise object
    Promise.resolve(thenable1); // returns Promise {: 'Future Studio'}
    console.log(Promise.resolve(thenable1)); // logs Promise {} ---> Promise {: 'Future Studio'}

    • @SteveGriffith-Prof3ssorSt3v3
      @SteveGriffith-Prof3ssorSt3v3  3 หลายเดือนก่อน +1

      Promise.resolve() is a promise, which is a microtask that gets called during a different point in the event loop.
      console.log() is a task on the main stack that gets called immediately. At the point where console.log is called, the Promise has not resolved yet.

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

    Thank you, Steve. Just quick question tho. Why do we use then twice?

    • @SteveGriffith-Prof3ssorSt3v3
      @SteveGriffith-Prof3ssorSt3v3  ปีที่แล้ว

      You can chain as many thens together as you want or need. Each one is the next step in your process

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

    4 years later this tutorial is holding up.

  • @taospencer1403
    @taospencer1403 5 ปีที่แล้ว

    Do you have any tutorials of setting up node js on shared hosting. I noticed your using node! but i'm unsure how to use ssh properly. I have downloaded bitvise and have ssh keys from hosting company but don't know how to use it all..?

    • @SteveGriffith-Prof3ssorSt3v3
      @SteveGriffith-Prof3ssorSt3v3  5 ปีที่แล้ว

      Not yet. Some day I will get to that though

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

      @@SteveGriffith-Prof3ssorSt3v3 Ok, Thank you for the speedy reply. Good tutorials..

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

    Line 21: could "ex" have some other name? I got confused by the fact that you have a variable "x" and now the "ex", is that just an unrelated letter match?

  • @CesarJuarezVargas
    @CesarJuarezVargas 6 ปีที่แล้ว

    What's the alternative to using the arrow syntax?

    • @SteveGriffith-Prof3ssorSt3v3
      @SteveGriffith-Prof3ssorSt3v3  6 ปีที่แล้ว

      Cesar Juarez-Vargas the alternative to arrow functions is just the basic function syntax.
      function f( ){ }

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

    I have problem in my destructuring in my project...can't find the error, please advise?

  • @sevdamurat4455
    @sevdamurat4455 5 ปีที่แล้ว

    Steve Griffith its interesting thatat lines 24-26 you didnt create a promise, nor return a promise BUT you returm a primitive value BUT still catch it with .then(). I was thinking that .then only works for promises. But it can work for any value? Right?

    • @SteveGriffith-Prof3ssorSt3v3
      @SteveGriffith-Prof3ssorSt3v3  5 ปีที่แล้ว

      Anything you return from a function inside a then method will be passed to the next then.

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

    Thank you for wonderful Explainantion Sir, please let me know when does data structure and algorithm comes in the process , when we should focus on that part? Thank you Sir

    • @SteveGriffith-Prof3ssorSt3v3
      @SteveGriffith-Prof3ssorSt3v3  3 ปีที่แล้ว +1

      learning data structures and algorithms is something that you learn along side everything else. There is no specific time for doing that. You also never stop learning more about these.

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

      @@SteveGriffith-Prof3ssorSt3v3 Thanks a lot Sir, Can you please post videos regarding data structure and algrotihms where we can learn about it

    • @SteveGriffith-Prof3ssorSt3v3
      @SteveGriffith-Prof3ssorSt3v3  3 ปีที่แล้ว +1

      @@aravindm6124 Please post any requests in the comments here - th-cam.com/video/LCezax2uN3c/w-d-xo.html
      and upvote ones you like.

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

    I have watched 100 tuts on promises and still do not understand them. will give it a shot as I am not giving up. Will edit later.

    • @SteveGriffith-Prof3ssorSt3v3
      @SteveGriffith-Prof3ssorSt3v3  3 ปีที่แล้ว +1

      They are really quite simple. A promise is an asynchronous task wrapped in a function. The task can work or fail. The task function has two callback functions. It calls one if the task was successful and the other if it failed.
      If you don't understand callbacks are - th-cam.com/video/uPCxgnLOuiQ/w-d-xo.html
      If you don't understand what asynchronous means - th-cam.com/video/Q-Zmc0E0GYY/w-d-xo.html

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

      @@SteveGriffith-Prof3ssorSt3v3 Thanks.

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

    /*
    Promises
    Wrappers for any asynchronous callback. Don't have to be wrappers. We make a call and we don't know when it's going to happen.
    AJAX calls, reading files, timeouts, geolocation, talk to a database, etc.
    Anything that would use a callback function.
    Use them to get rid of callback hell.
    fetch() returns a Promise
    A promise is a promise to return a response that's resolved or rejected ??
    */
    var result = multiplyTwoNumbers(5, 10)
    console.log(result)
    var photo = downloadPhoto("localhost/cat.jpg") //needs to retrieve the image
    //console.log(photo) will be undefined
    const rand = () => Math.floor(Math.random() * 10) + 1
    let p1 = new Promise((resolve, reject)=> {
    let x = 5
    resolve(x) //calling this will call then()
    // reject(x) //calling this will call .catch (only one of them can occur, either a resolve or a reject, not both)
    })
    p1.then((ex) => { //resolve(x) goes to ex
    console.log(ex)
    return ex
    }).then((x)=>{
    console.log(x)
    }).catch((exx)=>{ //Used if an error occurs
    console.log("caught", exx)
    })
    const rands = () => Math.floor(Math.random() * 10) + 1;
    let p1 = new Promise((resolve, reject) => {
    let x = 5;
    let num = rands()
    setTimeout(resolve, 1500, num) //calls resolve after 1.5 seconds
    });
    p2.then((ex) => {
    console.log(ex);
    return ex * 2
    })
    .then((x) => {
    console.log(x);
    })
    .catch((exx) => {
    //Used if an error occurs
    console.log("caught", exx);
    });
    fetch().then().then().catch() //another syntax

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

    All the video I saw this one is the best to understand the promise, thanks