- 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
1.Introduction2 lessons, 07:42
1.1Introduction02:12
1.2Setup05:30
2.Language Fundamentals8 lessons, 1:00:53
2.1Variables06:33
2.2Data Types11:28
2.3Arithmetic, Assignment, and Comparison Operators10:24
2.4Unary, Logical, Comma, and Spread Operators09:02
2.5Operator Precedence03:50
2.6Reserved Words04:17
2.7Strict Mode04:34
2.8Functions10:45
3.Data Structures5 lessons, 22:52
3.1Arrays04:29
3.2Objects04:30
3.3Sets04:57
3.4Maps04:21
3.5Weak Maps and Weak Sets04:35
4.Controlling Program Execution7 lessons, 37:06
4.1Conditionals07:49
4.2Switch Statements04:41
4.3The For Loop06:39
4.4The `for .. in` Loop05:17
4.5The `for .. of` Loop04:02
4.6Iterators05:03
4.7While Loops03:35
5.Using JavaScript13 lessons, 1:44:36
5.1Working With Strings09:32
5.2Template Literals05:46
5.3Working With Numbers06:57
5.4Working With Arrays12:53
5.5Iterating and Transforming Arrays07:33
5.6Working With the Object Type13:55
5.7Object Literal Extensions06:45
5.8Working With Object Instances06:45
5.9Getters and Setters05:00
5.10Custom Objects11:28
5.11The `Math` API04:54
5.12Working With Dates and Times08:10
5.13The `Array` Constructor04:58
6.Functions8 lessons, 56:07
6.1The `this` Object06:15
6.2Working With Functions10:11
6.3Scope07:37
6.4Arrow Functions06:59
6.5Generator Functions08:13
6.6Closures05:00
6.7Prototypes06:26
6.8Default and Rest Parameters05:26
7.Miscellaneous6 lessons, 52:39
7.1Destructuring Assignments08:09
7.2AJAX08:30
7.3Regular Expressions10:51
7.4More About Regular Expressions08:38
7.5Classes06:48
7.6ES Modules09:43
8.Working With the DOM6 lessons, 37:39
8.1Selecting HTML Elements05:02
8.2Manipulating HTML Elements07:40
8.3DOM Traversal05:25
8.4Adding and Removing Elements04:45
8.5Creating Elements and Other Nodes04:39
8.6DOM Events10:08
9.Web APIs4 lessons, 17:41
9.1The Selector API03:03
9.2Geolocation05:29
9.3Web Storage05:24
9.4Web Workers03:45
10.Asynchronous JavaScript5 lessons, 26:23
10.1Promises09:52
10.2Promise Chaining05:11
10.3The async Keyword03:21
10.4The await Keyword04:04
10.5More About async and await03:55
11.Conclusion1 lesson, 00:43
11.1Conclusion00: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.