7 days of WordPress plugins, themes & templates - for free!* Unlimited asset downloads! Start 7-Day Free Trial

Next lesson playing in 5 seconds

  • Overview
  • Transcript

1.2 Using JavaScript Promises

In this lesson we will use promises to control the styling of a page when it loads. First we will use just one promise. After that, we will chain some promises together.

Code Snippet

Here is an example of creating a promise:

var myPromise = new Promise(function(resolve,reject){
    setTimeout(function() {
        resolve("Timeout elapsed");
    }, 10000);

We can then await the resolution of the promise with:

    console.log('Promise resolved: ' + result);
    console.log('Rejected because: ' + reason);

Related Links

1.Using JavaScript Promises
2 lessons, 09:07


Using JavaScript Promises

1.2 Using JavaScript Promises

Hello everyone. I am Reggie Dawson. Welcome to the JavaScript Promises coffee break course for Tuts+. Now if you have done any work with JavaScript you have at least heard of, if not used Promises. Many popular frameworks and libraries have adopted Promises as opposed to using callbacks. Why Promises are so cool is that they allow us to perform a task without holding up our code while they wait for the task to complete. Promises is often used in HTTP requests where the data may not be available immediately. Instead of waiting for the download to complete we can continue setting up our app. Eventually we will get the data and then we can do something with it. In the meantime we initially get a promise which is just that, a promise of some data to come. Previously, we needed to use a separate library to employ Promises but it is now a part of ES5. As a result we don't need to do anything special to use Promises in our projects. Let's set up a sample project to explore how Promises work. First we will create an HTML file. Now this is just a basic HTML file that I generate it with the File and New From Template command in Cloud9. Of course if you aren't using Cloud9 you can just duplicate this HTML file. And the only other thing we're going to add to this HTML file is a reference to our app.js file. Next let's create the app.js file. First we will use the Windows on load event to fire off some functions when our page loads. Here, we have defined the init and somethingElse functions that are going to run when this page loads. After that we're going to create our init function. And inside of this function, the first thing we would do is create our promise. The syntax for creating a promise is new promise followed by a function this function will have the arguments of resolve and reject which are the two results we can have for our promise. Next we're going to add the set timeout method. Now, here we are using the static promise resolve method after ten seconds to return a message. We can also resolve using an array or even another promise. What we resolve here is then passed on to the next part of the promise. The then method returns a promise and handles the success in error callbacks of our promise. In the then function we will log our result and then we will change the background color. Now after that we will use the catch method for error. Bare in mind that both of these callbacks are optional and we don't have to use them if we don't want to. The catch method will return the reason our promise failed if it does. Now the last thing we need to do in this file is that the something else function. Now all we are doing in this function is logging when it executes. Now considering the order of the functions, the log for the somethingElse function should appear after the log for the Promises. Let's save our work in preview. If you are using Cloud9 like I am, we can just open the index.html page and click Preview. Now if we open up the developer console, we will see there's something else function log appears before the background change log. What happens with promises is that we return our promise and our code continues on its merry way. Once our promise resolves then the method executes and our console log is generated. Let's build another project that uses promises. Perhaps the client likes our fade to black effect but they want more. They want a message to appear, and then after that their logo. This is perfect for promises. First, we will create our index.html file. This file is similar to the last one except we're going to add a few more tags. The first tags is an H one with an ID of HD, we also have an inline style that sets the display to none, and sets the text color to white. The following two age four tags also have inline styles that are setting the display to none, after that, create your app.js file. Again, we will start off with the onload event followed by our init function. First, we will set some variables in our init function. Here we are grabbing our HTML elements and then we're setting up some values that we're going to check later. After that we're going to add a function. The first thing we're going to do in this function is create a new promise. Then we're going to add another function. The first thing this function is going to do is set our background color. Then we set the background ready value to true and resolve the promise. We are also logging the result so we can see what's going on with our promises and when they fire. And then following that we have our timeouts at the eight seconds before calling our set back function, then after that we're going to return our promise. Now this function is doing the same thing as before changing our background to black then we're going to add a second function. Here we are creating a second promise, and again we're following that promise with the function. This function checks the background ready value and sets the message to display it also sets the message ready value. After that we are resolving the promise and logging the result. Now if background ready is not true, we will display the error message and reject the promise. The reject method works just like a resolved, but it returns the cause of the reject. In this case it is because the background has not been set. Then we have our timeout calling our check background function after five seconds and then we return our promise. Finally, we have our third function that follows the same pattern. We have our promise followed by a function that is checking if the background ready and message ready has been set. If they have we are going to display our heading and resolve the promise. If they aren't we will display our error and reject the promise. Finally, we have a timeout calling our check all function after three seconds. After that all we have to do is use our then method to deal with our promises. All we are doing is logging the result of our promises. Go ahead and save your project and preview. If you look at the console, we see something failed immediately. This is the third promise which is set to three seconds. When it finds both values falls it immediately rejects. Then promise 2 is rejected because its value is not set yet. If you notice we get uncaught errors, this is because we didn't set up our catch methods. Now the first promise works fine. It just causes everything else to fail. Let's reverse the timeout so make the first one three seconds and the third one eight seconds. And then save and preview again. It works as expected now but there's another way that we can employ these promises. Set the first time out to eight seconds again and the third one the three seconds. Next I'm going to comment out our then statements, and instead I'm going to chain our promises together. When we create promises, we have the ability to chain them together. The return promise will be passed to the next promise in the chain, and if we wanted, we could easily pass values from one promise to the next. What do you think will happen now? Let's save and preview again. Now if you look at the console the then method for all of our promises fired immediately but we didn't get a failure. What happens is that the second promise doesn't do anything until it receives a result from the first promise. As a result, it's time out doesn't start until the eight seconds pass and the first promise resolves. After it resolves the five second start for the second promise. The third promise is just waiting till the second promise finishes, and then it's time out start. As you can see chaining the methods together has a different result than if you use the statements independently. I hope you have gained a better understanding of promises and can come up with some cool ways to use them in your projects.

Back to the top