Unlimited WordPress themes, graphics, videos & courses! Unlimited asset downloads! From $16.50/m

Next lesson playing in 5 seconds

Cancel
  • 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.Introduction
2 lessons, 07:42

1.1
Introduction
02:12

1.2
Setup
05:30

2.Language Fundamentals
8 lessons, 1:00:53

2.1
Variables
06:33

2.2
Data Types
11:28

2.3
Arithmetic, Assignment, and Comparison Operators
10:24

2.4
Unary, Logical, Comma, and Spread Operators
09:02

2.5
Operator Precedence
03:50

2.6
Reserved Words
04:17

2.7
Strict Mode
04:34

2.8
Functions
10:45

3.Data Structures
5 lessons, 22:52

3.1
Arrays
04:29

3.2
Objects
04:30

3.3
Sets
04:57

3.4
Maps
04:21

3.5
Weak Maps and Weak Sets
04:35

4.Controlling Program Execution
7 lessons, 37:06

4.1
Conditionals
07:49

4.2
Switch Statements
04:41

4.3
The For Loop
06:39

4.4
The `for .. in` Loop
05:17

4.5
The `for .. of` Loop
04:02

4.6
Iterators
05:03

4.7
While Loops
03:35

5.Using JavaScript
13 lessons, 1:44:36

5.1
Working With Strings
09:32

5.2
Template Literals
05:46

5.3
Working With Numbers
06:57

5.4
Working With Arrays
12:53

5.5
Iterating and Transforming Arrays
07:33

5.6
Working With the Object Type
13:55

5.7
Object Literal Extensions
06:45

5.8
Working With Object Instances
06:45

5.9
Getters and Setters
05:00

5.10
Custom Objects
11:28

5.11
The `Math` API
04:54

5.12
Working With Dates and Times
08:10

5.13
The `Array` Constructor
04:58

6.Functions
8 lessons, 56:07

6.1
The `this` Object
06:15

6.2
Working With Functions
10:11

6.3
Scope
07:37

6.4
Arrow Functions
06:59

6.5
Generator Functions
08:13

6.6
Closures
05:00

6.7
Prototypes
06:26

6.8
Default and Rest Parameters
05:26

7.Miscellaneous
6 lessons, 52:39

7.1
Destructuring Assignments
08:09

7.2
AJAX
08:30

7.3
Regular Expressions
10:51

7.4
More About Regular Expressions
08:38

7.5
Classes
06:48

7.6
ES Modules
09:43

8.Working With the DOM
6 lessons, 37:39

8.1
Selecting HTML Elements
05:02

8.2
Manipulating HTML Elements
07:40

8.3
DOM Traversal
05:25

8.4
Adding and Removing Elements
04:45

8.5
Creating Elements and Other Nodes
04:39

8.6
DOM Events
10:08

9.Web APIs
4 lessons, 17:41

9.1
The Selector API
03:03

9.2
Geolocation
05:29

9.3
Web Storage
05:24

9.4
Web Workers
03:45

10.Asynchronous JavaScript
5 lessons, 26:23

10.1
Promises
09:52

10.2
Promise Chaining
05:11

10.3
The async Keyword
03:21

10.4
The await Keyword
04:04

10.5
More About async and await
03:55

11.Conclusion
1 lesson, 00:43

11.1
Conclusion
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