Unlimited Plugins, WordPress themes, videos & courses! Unlimited asset downloads! From $16.50/m
Ecma 1
  • Overview
  • Transcript

6.1 Promises

In this lesson we’ll take a look at native JavaScript promises. A promise is a special type of object that represents an operation that hasn’t completed yet, but which is expected to return a value at some point.

Further Reading

6.1 Promises

Hi, folks. In this lesson, we're going to look at promises in ES6. For years now, we've used various libraries to implement the concept of promises, but finally, with ES6, they're now native. A promise represents an action that hasn't yet completed, and allows us to add handlers for an eventual success or failure of an asynchronous action, like a HTTP request. Promises are useful for when we want to get a single one off results that may happen at some point in the future. They aren't so useful for things that occur repeatedly, like clicks on a button, for example. In this case the usual event model is fine. In ES6 a promise is an object created using the promise constructor. We need to pass a function to the constructor with call backs to resolve or reject the promise. Inside the function we passed to the constructor, which is known as an executor function, we can then invoke the resolve or reject functions as appropriate depending on what we're trying to do. Let's just keep things simple for this example, and randomly resolve or reject the promise. We use a simple ternary expression with a condition that checks whether the result of Math.random is less than 0.5. If it is we can resolve the promise. If not, we reject it. This should give us a roughly 50% resolution or rejection rate. We can pass whatever value we want to the resolve or reject methods. In this case, we can just pass a string indicating success or failure. Now that we have our promise object in the my promise variable we can use the ven method to add success and failure handlers to the promise and invoke the executor function The then method takes two arguments which are the success and failure handlers, although, officially they're referred to as fulfillment and rejection handlers. These handlers are set as the resolve and reject arguments that are passed to the executor function. Inside them both we can just log the message. Inside them both we can just log a simple message to the console. An object that has a then method is said to be thenable, so this is a term you'll likely come across when reading about promises. The appropriate handler will either be invoked at some point in the future when the promise resolves or rejects, or if the promise is already settled the appropriate handler will be invoked immediately. So, let's take a look in the browser now. So, it looks like we're missing a closing parentheses, and that is on line 13. Let's just go back and fix that quickly. And let's try that once again. So that time the promise was resolved, but that time it was rejected. A promise object may be in one of three different states. Fulfilled is when the promise has been resolved, and rejected is when the promise has been rejected. It could also be in the pending state which it's in before it has fulfilled or rejected. Technically, a fourth state is settled which is when it has either been fulfilled or rejected. Remember that a promise can only be fulfilled or rejected once. The then method also returns a promise which is resolved with either the original settled value of the first promise or the return value of whichever handler was called. So the then method is chainable. Let's make a couple of changes to the example code. First of all, let's return true form the fulfillment handler and false from the rejection handler. We can then add another then method chained to the first then method And let's try running that once again in the browser. When the promise is resolved we see the value true, Aand when the promise is rejected we see the value false. So, the value passed to each handler and logged to the console is the return value from whichever handler is invoked. As well as the then method we also have the catch method which works in a similar way to then, but it allows us to add just a rejection handler. The example that we've looked at so far, while illustrative, doesn't really show the true power of the promise in action. Before we finish up for today let's take a look at a much more realistic scenario where a promise really excels, an Ajax request. We can make a request to the numbers API. This is a fun API at http://numbersapi.com. So let's use a promise with this API to handle working with an Ajax response. So let's comment out the code that we've added so far. And let's make a start by adding a function that we can use to make requests, and which will return a promise for us to consume. We can pass the function, the URL, that we want to make the request to. Inside we can return a new promise. Inside the executor function we can create create a new Ajax request. We can then add a ready state change handler. And let's check whether the ready state is equal to 4. Once the ready state is set to 4 we can then check the status code and either resolve or reject the promise accordingly. Lastly, we can open and send the request. This should be what we need to do here. Our get number fact function returns to promise. So to use it we can just invoke the function and chain the then method on with the handlers for success or failure. We need to pass the URL as a parameter to our getNumberFact function. We can use arrow functions to log either the response from the numbers API or the status text if something goes wrong. So let's take a look in the browser now. And it clearly works because we have a number fact there. And this should change each time we refresh the page. For clarification on the terminology around the different states that a promise object may be in, Domenic Denicola, has an excellent write up called States and Fates up on GitHub. I'd recommend that you have a good read through this document. So, in this lesson we looked at native promises in ES6. We saw that a promise is an object created with the promise constructor and which usually has a then method. We saw that we can create a promise and use an executor function to resolve or reject a promise as appropriate. We learned that we can then use the then method to attach handlers for success or failure of the promise, or use the catch method to catch just the failure. Thanks for watching

Back to the top