Bummer! This is just a preview. You need to be signed in with a Basic account to view the entire video.
Start a free Basic trial
to watch this video
In this video you'll see some examples of Promises applied in real-world scenarios.
-
0:00
Now that you've seen promises in action in your own code,
-
0:03
I'll show you some examples of promises in real world scenarios.
-
0:08
Sequelize is a Node.js ORM, a way for Node.js to talk to a database.
-
0:14
Let's look at the example code here.
-
0:17
Sequelize wants to synchronize the schema we've defined here.
-
0:22
Once that's done, it wants to create a user.
-
0:26
Once the new user has been created, after an asynchronous call to the database.
-
0:31
The promised value of the new user
-
0:34
is passed along to the next promise to resolve.
-
0:38
Remember, you want to use promises when asynchronous calls are happening.
-
0:42
And not to block the system where the Node.js application is running.
-
0:47
You'll find that the ORM model layer in many JavaScript frameworks
-
0:51
has this promise pattern.
-
0:53
The same goes for bookshelf.
-
0:55
Once the results are fetched, there's a then and a catch of a promise.
-
1:02
You may have heard of Ember j.s..
-
1:03
It's a front end framework for creating user interfaces.
-
1:08
Without going into too much detail,
-
1:10
Ember.js uses promises to handle asynchronous routing.
-
1:14
To perform asynchronous operations and handle code in a more human readable way.
-
1:21
And then there's the $q service in Angular,
-
1:23
which is used to wrap anonymous functions in a promise.
-
1:26
In other words, Angular has promises built in.
-
1:30
The $q function is basically a promise constructor requiring resolve and
-
1:35
reject handlers.
-
1:37
JQuery has a version of promises called deferred objects.
-
1:41
Take a look at this example code.
-
1:44
JQuery is performing an AJAX call, it returns a deferred object.
-
1:49
In other words, jQuery's version of a promise, that you can use the then method
-
1:55
to handle the resolution and the rejection of the promise.
-
2:00
Finally, new browser APIs are now using promises.
-
2:04
For example, fetch, which is a modern way to perform AJAX requests,
-
2:09
returns a promise.
-
2:10
In this example, the flowers image is downloaded asynchronously.
-
2:16
Once it's downloaded, the raw data is returned.
-
2:21
This promise is resolved and
-
2:22
then converted into a data URL for the selected image.
-
2:28
Then there's the Battery Status API.
-
2:30
This is used to get the battery charging information for laptops and mobile phones.
-
2:35
If you know the battery is at a certain percentage,
-
2:39
you may want your application to save the information or warn the user.
-
2:43
There are many more instances of promises in the wild.
-
2:47
And now you know how to use them.
You need to sign up for Treehouse in order to download course files.
Sign up