Unlimited Plugins, WordPress themes, videos & courses! Unlimited asset downloads! From \$16.50/m
FREELessons:65Length:7.1 hours

• Overview
• Transcript

# 10.1 Promises

In this lesson we'll look at native JavaScript promises, a special type of object that represents an operation that hasn't completed yet, but which is expected at some point.

Key terms:

• new Promise()
• resolve
• reject
• then

## 11.Conclusion1 lesson, 00:43

### 10.1 Promises

Hi folks. In this lesson, we're going to look at native JavaScript promises. 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 result 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. 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 a promise. The function we pass to the constructor, which is known as an executed function, receives functions that can be used to resolve or reject the promise. We can then invoke the resolve or reject functions. Inside the execute to function 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 condition here to check whether the result of math.random is less than 0.5. If it is we resolve the promise, but if not, we reject it. We can pass whatever we want to the resolve or reject methods. In this case, we can just pass a simple string indicating success or failure. Now that we have our promise objects in the my promise variable. We can use the then method to add success and failure and blues to the promise and invoke the execute to 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. Inside each of them, we can log a simple message. In this case, an object that has a then method is set to be tenable, which is a term that you likely come across when working with promises. The appropriate handler will be invoked at some points in the future when the promise resolves or rejects. These states of being either resolved or rejected, are collectively known as settled. So when a promise has been settled, it has been either resolved or rejected. Before a promise has been settled, it is in a state known as pending. As soon as the promise settles the appropriate handler, either the success or failure handlers will be invoked immediately. So let's just take a look at what we've got so far in the browser's console. So we can see that this time the promise was resolved. Let's refresh the page. And we can see that this time the promise was rejected. So just to recap, then the promise objects may be in one of three different states. Pending is the first state and then it may be either fulfilled which is when the promise has been resolved. Or rejected, which is when the promise has been rejected, and both the resolved or rejected statements together, are known as settled. Remember that a promise can only be fulfilled or rejected once, so it can only be settled once. The then method itself also returns a promise. And that promise is resolved with either the original settled value of the first promise or the return value of whichever handler either success or failure returned. So the then method itself is chainable. So let's just go back and update our example. So in the success handler that we pass to the first their method we returned true after we logged to the console. And in the failure handler that we pass to the first their method, we return false. In the second then method, which we've chained on to the end of the first one, we can just log this value depending on whether the success or failure handler, the second then method is called. So let's go back to the browser again. And we see true in the console because the first promise was fulfilled. And let's refresh it a few times. And we see that when the first promise gets rejected, the second promise is resolved with force. So the example that we've looked at so far, well, illustrative doesn't really show the true power of a promise in action. Before we finish up for this lesson, let's look at a much more realistic scenario where a promise really excels. An Ajax request. So let's use the numbers API once again, but this time, use a promise to handle working with the response. So let's comment on the first example first of all. And let's start by adding a function that can be used to make an Ajax request. So we've added a function called GetNumberfact and that accepts a URL. So the GetNumberfact function returns a new promise inside the executor function then we can create a new Ajax request. And let's now add an onload handler for the XML HTTP request object that we just created. And inside the on load handler, we can just check that the status of the request is 200, which would indicate a successful response. So when the response is successful, we want to resolve our promise. So we check the status of the request object and if that is equal to 200, we can resolve our promise and pass it the response text, which should contain the response from the server. If the status is not 200, then we can reject top promise instead and pass it the status text, which should indicate why the request failed. So lastly, we can open and send our. So this should be what we need to do inside our getNumberFact function. So now we can invoke this function, pass it the URL that we want to make a request to, and add a then method which handles the response or error. And let's now check the output in our browser. So we can see that it was successful and it gave us a random factor by a number and that number happen to be 2,055,001. And that is apparently the number of people employed by Walmart in 2007, which is fascinating but let's get back to the code. So we saw a successful requests there. What about if we give the numbers an API a really big number. Let's try that. And see if they got a fact for that number. They do have a fact for it, but it looks like a generic fact which just says the number is a boring number. So let's try a really tiny number instead. Okay, so we saw that we can trigger an error by sending it a bad request. And in this case, we just see the text Bad Request logged out to the console. So in this lesson we look at native promises in JavaScript which were only added in ES2015. 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 either resolve or reject the promise as appropriate. We learned that we can attach handlers for success or failure to the promise using the then method. In the next lesson, we're going to look at promise chaining. Thanks for watching.

Back to the top