Heads up! To view this whole video, sign in with your Courses account or enroll in your free 7-day trial. Sign In Enroll
Preview
Video Player
00:00
00:00
00:00
- 2x 2x
- 1.75x 1.75x
- 1.5x 1.5x
- 1.25x 1.25x
- 1.1x 1.1x
- 1x 1x
- 0.75x 0.75x
- 0.5x 0.5x
An example of using promises to handle asynchronous tasks in Express.
An example of what using promises to perform two asynchronous operations might look like:
app.get('/:id', (req, res) => {
getUser(req.params.id)
.then((user)=>{
return getFollowers(user);
})
.then((user, followers)=>{
res.render('profile', {title: "Profile Page", users: user, followers: followers});
})
.catch((err) => {
res.render('error', {error: err});
});
});
Related Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign upRelated Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign up
Callbacks work fine for
asynchronous actions.
0:00
But as we've seen, they can get messy and
0:03
hard to follow pretty quickly once
you've started nesting callbacks.
0:04
Promises do the same thing for us in a way
that tends to be more straight forward and
0:08
easy to read.
0:13
Promises allow us to clearly outline
the order in which things need to be done,
0:14
by chaining functions together in
the order we wish them to execute,
0:18
rather than nesting them
one inside of another.
0:22
Remember, we're dealing
with eventualities here.
0:26
Writing code to deal with info from a data
store whenever we happen to receive it.
0:29
When this data becomes available, a
promise promises to do something with it.
0:33
Let's see what that looks like.
0:38
I'm going to copy and paste our previous
code, and delete the code inside.
0:40
Remember to delete the callback,
I'll then comment out our previous code.
0:51
Let's also add comments denoting that this
will be an example of using promises.
0:59
Functions that return a promise give us
access to the then and catch methods.
1:06
Inside the route,
I'll call the getUsers function and
1:11
chain calls to the then method and
the catch method.
1:14
These methods allow you to chain
different actions in a cleaner way.
1:22
You're saying, almost in plain English,
run this function then do something else,
1:26
then potentially do something else,
and even something else after that.
1:32
And when you're done running your chain of
functions, any errors fall into the catch
1:36
method, where you can handle
them in a more streamlined way.
1:40
To be able to use then in catch,
1:44
however, getUsers is going
to need to return a promise.
1:46
Let's do that now, inside the getUsers
function we'll start by creating a new
1:50
promise and returning it.
1:54
The new promise takes a callback
to execute after it's created.
1:59
Inside this callback, we need to
perform an asynchronous operation and
2:06
define what should happen if
the action is successful,
2:11
and what should if
the action isn't successful?
2:14
To do that, the callback accepts
two parameters, resolve and reject.
2:17
Inside the promise for
asynchronous operation,
2:26
we can do something similar
to what we did before.
2:28
First we need to read the data.json
file using Node's FS module.
2:32
Inside the readFile methods callback
we'll again define the error and
2:48
data parameters.
2:51
If there's an error, we'll reject the
promise by calling the reject parameter
2:55
method and pass in the error.
2:59
Else if everything goes to plan,
we'll parse the JSON formatted data and
3:05
send it to a variable called users.
3:09
And by the way, we're doing this because
the readFile method gives us the data from
3:16
the data.json file as a String,
so we need to parse to JSON.
3:21
Now, instead of calling a callback
function we resolve the promise by calling
3:24
the resolve parameter
method passing it to data.
3:29
So we're saying here, when getUsers
is called, create a new promise,
3:36
read the file, and if reading the file
isn't successful give us the error,
3:40
and if it is successful gives us the data.
3:46
Now the getUsers returns
a promise we can use the then and
3:49
catch methods that are provided
to us on the promise object.
3:53
The then method accepts a function, so
let's pass it an anonymous function.
3:56
Inside this function we'll need to define
a parameter called users to gain access to
4:03
the data provided by get users.
4:08
Remember, we've programmed getUser so
that it either provides the data or
4:11
provides an error.
4:15
So we've called getUsers,
we have the users.
4:17
Now we can render the page.
4:20
Before we move on, let's save and
fire this up and make sure it's working.
4:32
And it is, that's great.
4:39
If the getUsers function encounters an
error, it'll be passed to the catch method
4:41
which also accepts a callback
to run when errors are caught.
4:46
We'll define a parameter for
the error and render the error page
4:54
Let's use JavaScript's native error
constructor to throw a fake error in
5:05
our then function to make sure
the user will see an error page.
5:09
So up here,
we'll just quickly throw a new error.
5:12
Let's check this out and
great, it's working.
5:21
I'll go ahead and delete this error.
5:25
So you see, instead of having
nested callback functions,
5:28
we can instead chain then functions
to achieve different tasks.
5:31
Remember the example we looked at
earlier of doing more than one
5:36
asynchronous action, and
how messy it became using callbacks?
5:39
See the teacher's notes for
5:43
an example of what that code
might look like using promises.
5:44
In the next video, we'll look at an
approach that's even more straightforward
5:48
to follow, async and await.
5:51
You need to sign up for Treehouse in order to download course files.
Sign upYou need to sign up for Treehouse in order to set up Workspace
Sign up