Join Ray Villalobos for an in-depth discussion in this video What is the relationship between promises and callbacks?, part of Mastering Web Developer Interview Code.
In this case we're calling a function, the function has no name, so it's actually an anonymous function. We could just as easily call another function that we've created somewhere else. Callbacks are common on asynchronous events. The callback will be executed when something happens, in this case whenever a click event takes place. Now, there are a few problems with callbacks. The most notable is that callback code often suffers from clarity. More importantly callbacks can suffer from a lack of guarantees that the code inside them will be executed at certain times.
Now, in contrast promises provide a number of features and other safeguards including a execution guarantee and that means that callbacks and promises will never be called before the completion of the current event loop. Also, promises will resolve only once. It can't succeed or fail more than once and if a promise has succeeded or failed, it will call the correct callback even though the event might have already taken place. Promises are designed to be easily chained.
The result of one operation can lead to the start of another. If you do chain promises and there is an error somewhere along the line, the promise chain will stop which is a huge advantage with promises over callbacks. So, let's take a look at a traditional issue that we run into when we try to use callbacks and asynchronous events. So, in this case we're doing an ajax request right here and we're placing the results into this variable called artists and we're trying to print it out in here as well as down here, so one of these is not going to work and if we take a look at the console, so I'm in Chrome, I'll inspect and then I'll switch over to the console tab.
I'll notice that one of these printouts is printing out a variable as having an undefined value and it's actually happening down here. The problem is that I'm making the ajax request here, but before that ajax request has finished loading because it happens at some undefined time in the future I'm actually trying to output this variable and it doesn't yet exist and that's a problem because occasionally we would like to make sure that we do things but only after something else happens, in this case this asynchronous ajax request.
So, we can improve on that by making this into a promise. What I'll do is I'll use the return statement here to create a new promise. This is the constructor that you use to make promises and then in here this is going to require you to use a callback, so we'll use a function and then inside this callback you're going to want to use two different other methods or callbacks and we're going to call one resolve and the other one reject.
So, resolve is what is going to happen when everything that you're asking for in here will work correctly and then reject will obviously be a function that you execute when whatever you want to happen doesn't work, so we're going to grab all of this in here and what we can do then once we have this promise is instead of just assigning this to that variable, I'm going to grab this and use this resolve method and pass that along to that resolve method, so whenever this resolve happens, it's going to get the data from this JSON.parse operation.
Now, let's go ahead and delete this line 'cause we're no longer going to print that out in here. So, now we can use that promise once we try to load this data and use the then statement. So, the then statement is a special method in the promise object that will execute only if the promise is successfully resolved. So, then we're going to use a callback here and let's go ahead and make this wider, so we'll pass along whatever data we receive from the call to our resolve method, so here we're passing along the parsed data from the ajax call and it's going to be stored into this data variable and then we can console.log so we can do this console.log in here now.
And we don't want to print out artists because that information is actually in this variable called data, so let's go ahead and save that and when we refresh our page, you're going to notice that it's correctly printing out the artists as a result of our promise, so this is how promises work. Whenever you want to do something after something happens, then you can create a promise and once that promise resolves, then it's going do whatever you want using this then statement.
We can actually chain another then statement here and use another callback if we wanted to, so function(data) and then we can have it do something else, so console.log('finished') and in this simple way the finished output will happen if and only if this promise has resolved. So, that's cool 'cause we can do now a code outside. What would normally happen is we would put all this code right here but now we can execute things in order and make sure that they only happen as a result of a specific call, so this specific call will then once it's resolved cause this other stuff to happen, so let me show you a slightly more complicated version of this and this is going to actually load two different files.
There's something called data_schedule.json as well as data_artists. This is a more complicated version and let's make this bigger so you can see what's going on here. So, this ajax call is pretty similar except that now we can also use this reject method. The reject method will be called if the promise is unsuccessful in getting the data, so just like I called resolve whenever the information came through, I'm calling reject if for some reason this ajax call isn't successful.
I'm also adding a console.log right here, so because I'm actually loading two different things I want to identify which one I'm loading and so, I'm saying console.log getting and then the URL that I'm asking for right here. So, you can see that when this reloaded, it's actually telling you getting the data_schedule and then getting data_artists and that's great. So, what's really interesting is mostly happening down here. So, right here I am actually targeting an event on this button, so if I click on this button, it's going to display the data again and notice that here's the printout of that data and I'm also doing something pretty cool which is chaining, so I'm saying well, load the calendar information first and then I want you to do the following.
Just like we did before, output the data but then I'm saying something pretty interesting here, I'm saying also return another callback, so here is this other callback that we created called loadData and if we do this, then this second file, the artists.json file, the data_artists.json file is only going to be loaded if this other one has already been loaded, so the difference between this and what we had with that finished statement is that because we're passing along a promise in this return statement, this second file is only going to work if the first file has finished loading, so that's something that you can do with promises, that is pretty cool and then also we are saying if there's an error, so notice that essentially this then function takes two parameters, so this is one of the parameters, this is essentially what happens if everything resolves but then we can also pass a second parameter and this is another callback with what happens if the promise doesn't resolve or if it's rejected, then we can actually output something to the console and in this instance, if something happens to our promise and it doesn't execute, this other data will never be loaded, so we can be much more specific as to what happens as a result of a promise being fulfilled, what happens if it is rejected and then we can also chain things so that we can control whether or not a secondary promise or a secondary event takes place only if we want it to as a result of another promise and this what makes promises super powerful.
Connect with me in LinkedIn or just about any other social media network like Twitter or GitHub @planetoftheweb.
Skill Level Intermediate
Q: Why can't I earn a Certificate of Completion for this course?
A: We publish a new tutorial or tutorials for this course on a regular basis. We are unable to offer a Certificate of Completion because it is an ever-evolving course that is not designed to be completed. Check back often for new movies.