Press "Enter" to skip to content

ES6 Tutorial – #11 Promises (then / catch)


hey guys welcome back to the es6 series
in this video we’re going to take a look
at promises so what are promises you
might ask well the promise is basically
a language contract in es6 that’s been
added it precisely for having
asynchronous operations so in essence a
promise is simply an object that
represents an operation that has not
been executed yet and the thing about
promises is that one that promised
object is returned you can actually
attach callbacks to that object instead
of passing them into a function as you
would typically do with traditional or
old-style callbacks typically you don’t
create promises but yourself
promises are usually baked in libraries
like I said jQuery AJAX or also Axios or
you might even see in promises and
libraries like firebase they’re really
all over the place and like I said
typically you don’t clear them by
yourself using the promise constructor
most of the time you are essentially a
consumer of a library or a project that
already has promises baked into it in
order to see the benefits of using
promises let’s first look at an
older-style approach to handling
asynchronous operations and this style
has been very popular especially in
nodejs environment and the style I’m
talking about is the callback functional
style
so with callbacks imagine that we want
to execute a sequence of operations here
so for example we might have a login
function that expects an email as well
as a password imagine that this function
is going to create a an ajax request to
a server and the server is going to
validate the email as well as a password
and then it’s going to return a response
which is either going to be a success
response a 200 response we might get the
user object or it could be an error
response in which case there was a
problem with the email address or the
password so in order to continue
execution after the server has sent a
response back to the client
right after the validation has been done
this function needs to expect another
argument which is going to be a success
callback so this function would be
executed once the response from the
server is returned
but because the response from the server
could also be an error so meaning that
the request has failed we also need to
expect another callback which would be a
failure callback so in fact let’s create
this function right here let’s do log in
be an error function we’re gonna expect
a list of arguments like that okay
let’s have an empty body for now so once
that function is called like I said we
need to provide the email the password
and in fact let’s do something like this
that’s to Alex at gmail.com that’s not
about email of course for the password
let’s do a simple pass one two three and
then the success callback like I said it
needs to be a function so I’m going to
use error functions here and like I said
this function is going to execute and
whenever we get a successful response
from the server so you might imagine
then this function whenever we log in to
the server the server might respond with
the user object so we might expect to
receive a user object once the operation
succeeds but because there’s a
possibility that the operation might
fail due to network problems or simply
because we provided an invalid email or
password like I said we might also get
an error so we might have another
callback with the error now for the
error there are multiple different ways
to handle it but one way to do it could
be just to simply console.log the error
and that’s sufficient for this example
okay so once we get the user object what
we might want to do with the user object
is let’s say once we get the user we
want to load user profile so that would
be another function in the similar
fashion this load user profile function
would also expect a user that we get
from the login function right
once that function executes but it’s
also going to expect a success callback
as well as the error handler callback
right and the success callback might
return the profile object itself and for
the air typically would just be the
error object and in this example we
might just simply do console log the
error and then maybe lastly the last
thing you would want to do is for
example once you get the profile you
also want to load
profile posts for instance right so you
pass the profile you pass the success
callback and in this case we get to post
a function we also have a error handler
here and in there we look just to
console.log error for the post we would
do let’s just do simple auto log posts
so we have three nested functions in
here right log in load user profile and
low profile posts now back to the login
function because we don’t have any
server ready here I’m actually going to
simulate the HX call by creating a
simple set timeout so this is going to
create a timeout for us we’re going to
provide a callback function and this is
going to execute after one second
so to simulate this call I’m just gonna
say let’s say on the server you might
have a check if you have an email as
well as a password and of course
typically would also validate that this
signal exists in the database and the
password actually matches the hashed
password that you have stored in the
database but let’s say that we will do a
simple check if we have the email as
well as the password we’re going to
execute the success callback function
right and we’re also going to pass a
user object which the success callback
function expects so in this case the
user object let’s say it might have a ID
so we might do date now but also have a
name let’s do Alex and for instance we
might also do the email Alex at
gmail.com okay and then for the else
condition so if we did not provide the
email as well as the password we’re
going to we just want to call the
failure callback and let’s say we’re
going to pass a message that’s gonna say
email and password are required like so
now let’s create the second function
here so load user profile it’s also
going to be an error function load user
profile and that function is going to
expect let’s see for the argument list
it’s going to
expect the user but it’s also going to
expect again you can see a pattern here
it’s going to expect the successful back
as well as the failure all back and in a
similar fashion you would imagine this
will typically be an AJAX call so I’m
just going to set a timeout to simulate
that server call let’s set it to 1 1
second also so in there we might have a
check so if you provided a user in this
example you might imagine if you made an
actual call and you provided the user
object or the user ID inside of the we
class body so we want to have that check
and of course if you did not provide the
user we would need to call the failure
callback we might pass an error message
saying that user is required and then in
the success callback and let’s say we
call the success callback here we pass
an object I’ll be the profile so in
there let’s say we might have a profile
ID some ID and we might also have an
image so it might be a link to the image
of the profile when I’m just gonna put
some dummy data and lastly we also need
to have our load profile post function
right I have that as well and we’re
going to have a function that expects
profile and it’s also going to need to
have the two callbacks as usual okay
so once we have that I’m also going to
set a timeout to simulate a network
request so that provide a callback
function let’s also set it to one second
so it’s going to execute that for one
second and we’re also going to have a
checks if you provided a profile okay we
are just simply going to call the
success callback and we might want to
pass an array of posts so this will be
an array of objects and let’s say for
the first one you might have object some
kind of an ID I’m just gonna put one for
now and maybe title my post and then for
the second one let’s say we have any
if – the title would be my awesome post
okay
just some dummy data for now and of
course we can’t forget the error handler
in this case we would just call the
failure go back and I’m just going to
stir well clear out the log it’s already
executing but let’s also put profile is
required something like that and as you
see right here we get the output on the
right we get the object with the post
okay and for instance if I remove the
email address you might expect an error
to show up we get email and password are
required of course the same thing will
happen if I remove the password right
you’re gonna get the same error as well
let’s see there we go error now of
course if I for example did not provide
the user object if I but let’s say null
for the user object that’s gonna make
the second function fails so we’re gonna
get in here user is required and as you
might expect if I don’t provide a
profile if I just put null for that
function because it expects a profiling
here we actually have a check for that
profile we’re going to get an error
message it says profile is required so
what was the purpose of showing this
quite a complicated example what we had
to login first then we wanted to load
your profile anyone to load the post
well as you can see here all of these
actions are asynchronous and that’s why
the output on the right actually happens
with a bit of a delay every single
action every single function here
executes after a one second timeout’ and
you can imagine is that these functions
will be part of some kind of an API that
actually makes network requests one of
the flaws of this callback approach is
that it becomes cumbersome to deal with
nested or sequential asynchronous
operations once every operation is
scheduled to run after one another
so in this scenario we’ll basically end
up nesting the callback functions inside
of each callback that’s being executed
right
and notice that in here we sort of
created like a pyramid of coal box and
this long chain of deeply nested
anonymous function is actually referred
to as callback hell and even though this
approach works perfectly fine eventually
with more complicated more advanced
applications it becomes really difficult
to read through the code and track down
the changes and see what exactly is
going on at every single step and this
is where promises come in so we’re going
to refactor this example using promises
first of all instead of returning a
function from login I’m actually going
to return a promise so let’s return a
new promise object and the promise is
actually going to expect a function as
well now it’s not going to be just any
function this function is going to
receive two special arguments one of
them is going to be the resolve argument
and the other one reject now the way you
name them is up to you but the concept
is that basically the first argument
would be the function that executes and
the success scenario so everything went
well there was no errors the second one
executes whenever something Iranian US
or some failure happens and this is
similar to the success callback as well
as a failure call the callback that we
have to explicitly pass to the functions
whatever we call them so here for
example I call the load User Profile
notice that I receive the user object
but I also have to pass a function that
is going to receive the profile and then
it’s also going to have some logic
inside of it right this is going to be
quite different with promises as you’re
gonna see in a few seconds
we just cleared a lot for now and inside
of that function let’s actually put back
the set timeout call okay and instead of
calling the success callback in a
failure callback virtually going to call
resolve and we’re also going to call
reject okay like so remove those curly
braces now let’s refactor this second
one so we have another call back style
function here so instead of returning a
function we are going to return a
promise here and again the promise is
also going to have a similar shape it’s
going to receive
a function inside of that function we’re
just gonna put back the logic that we
had before I move attach set timeout
call so that’s just indented a little
bit let’s remove the old braces the same
thing goes for low-profile posts this is
also going to return a promise so we’re
just going to return new promise and
when we use the promise it’s basically
using the promise constructors it’s
going to create a promise object and the
same goes in here so we need to have a
function that is going to receive
resolve as well as reject and then the
same note of course we have to replace
success callback when resolved and also
failure callback will reject because
that’s how we call the parameters like I
said you can call them whatever you want
but basically the convention is to use
resolve and reject across the board and
inside of that function we’re gonna put
back the set timeout so the logic didn’t
actually change its going to be the same
but we also have to replace of course
resolve and reject like so now the way
that you handle promises is also going
to change
so before notice that we had to call
each function sequentially right and we
also had to pass the arguments so the
logon function expects an email as well
as a password but that function also
needs a callback function so everything
in here and the body of the function
that’s going to execute after the logon
function finishes and we also had to
provide the error handler because that
function might fail due to network
requests like I said or because the
email wasn’t valid with the password was
invalid word even if we didn’t provide
the email or the passwords all together
and you can really see that we had to
copy the air handlers for every single
function that we execute it so every
function we have to provide the success
callback for example here for the user
object the profile object post but every
time you’ll also have to provide the
error handler as well which is not very
efficient and that’s quite different
with promises so what promises instead
of doing it with the old-style
functional or Kobach approach where you
actually had to pass the callbacks or
arguments to the function in this
example the only two arguments are going
to be the email and the password and of
course this is going to change the
signature of those functions I forgot to
update them so we no longer need to
accept a success callback and the
frailer callback which is going to
accept e in this example for the long
M&E email and password for logging the
profile we need the user and for login
posts we need to profile ok and instead
of actually passing those callbacks as
argument functions we’re going to nest
another function call here and this is
going to be then function this function
is going to receive an argument that is
going to be another function a callback
essentially so in this example once we
log in we when we can expect to have a
function that accepts the user right so
we can have a function it accepts the
user and then you have some processing
logic inside of it let’s indent this
like so so we get a function that
accepts the user and we’re gonna get the
user object and then we can continue
doing whatever we wanted to do
afterwards now what about the error
handler there are two ways to handle it
one way would be to add another function
and this function would accept the error
and then of course inside of that
function we could just simply do console
log that error okay and that’s one way
to handle it let’s just keep it that way
for now I’m going to show you other ways
as well
now after that once we get the user
object we can also call load user
profile function okay that function is
going to accept the user now after that
load user profile function executes we
can have another than call okay and that
function that then a massive call is
also going to expect another callback in
this example we’re going to have a
callback that gives us a profile and
then we can continue the logic inside of
it now like I said you can also copy the
error handler as well and put it in
there but in this case it sort of
becomes tedious and you’re
OOP locating the air handlers is
actually a simpler way to handle it so
instead of putting the air handler as a
second argument you could actually have
another clause that’s going to be called
as catch and instead of that catch
you’re just basically going to pass
another callback that callback is going
to expect an error in this example just
a string a message and it’s going to
console.log that error and you could
have just one single catch clause and
it’s gonna be at the end of your event
clauses the first once we get the
profile we can call the function load
profile post okay we’re gonna pass the
profile and once that function executes
we’re gonna have event clause which is
going to expect the posts and finally
once we get the post we can just
console.log those posts okay and of
course all of that other stuff is gonna
be gone and as you can see here we
actually get undefined and that’s
because we need to return the result of
that function for every function that we
call so in this example actually because
we just have a simple operation I’m just
going to take advantage of the implicit
return keyword I’m just gonna put the
function call on the same line removing
me curly braces I’m gonna do the same
for the profile as well so I’m just
gonna bring it on a single line and I’m
gonna do the same for post because we
just want to console.log them out so you
end up with a structure that looks
something like this so you can see that
we get the same results as before we
gather to post objects on the right this
is the exact same call as we had before
but this approach is actually shorter to
write and it’s easier to follow so in
this example we’re calling the logon
function with the email as well as the
password right once in that function
executes then we want to execute another
function this callback function is going
to receive the user object why you might
ask well the user object is returned
from the result call that put it inside
of the promise so if everything goes
well if he provided the email as well as
the password this condition succeeds
it’s true
and that’s why we want to resolve with
an object essentially a user object that
contains
Diann name as well as the email so that
user object is being returned to this
callback function and once we get the
user we execute lo user profile once
that function executes then we want to
call another callback that callback is
going to load profile post with the
profile and after that then we’re going
to glass they call another function
that’s just going to console.log the
posts and lastly if anything fails which
is going to use the error handler
function or callback here this fellow
using Kovaks is known as asynchronous
function call so instead of passing
callbacks as arguments to the function
as we did with the old tail callbacks in
HT every function we basically create a
promise object so here we have a promise
object we create a using a constructor
the same for load user profile and load
profile box so we create promised
objects and once that promise object is
returned we can actually attach
callbacks to that promise so in this
scenario we attach the then call to that
promise that’s returned from the login
function right and we do it for every
single function here for login for load
user profile and load profile’ post and
essentially what we end up doing is we
create a chain of van calls this chain
is also known as promise chain and the
thing to note here is that every single
van call is going to return a new
promise that is going to be rejected or
resolved after the callback finishes
execution
so the first then call is going to
execute only after the login function
succeeds the second van is going to
execute not only after login function
succeeds but also after this than call
or the load user profile call succeeds
and as you might imagine the third then
is also going to execute after logon
function succeeds after the load user
profile succeeds and after load profile
posts also succeeds I already pointed
out that before we had to provide air
handlers for every single function that
we called along with the success
callback well in this scenario would
just have one catch Clause that is going
to catch all sorts of errors so if
anything down the road fails for example
something fails analog and
oran load user profile’ function or for
that matter in low profile pose if any
failure happens it’s always going to be
passed down to the catch handler air
handler and in this scenario is just
basically going to be log to the console
so as you can see here the advantages is
that we get a chain of callback
functions which basically makes it more
readable for us because it allows us to
have multiple phone calls that run a
synchronously one after another one and
unlike callbacks we never actually go
more than one level deep so everything
is sort of like flattened and it’s just
easier to read know the promised object
also has a few static methods one of
them is all an essentially accepts an
array of promises such that when all of
the promises are resolved you are just
going to execute a single callback
basically when everything finishes
successfully and if anything fails well
as you might expect it’s going to go to
the catch clause for which you have to
provide your own callback and another
static methods I’m just going to mention
is also race so race is similar except
that it’s going to execute once one of
the promises is resolved so you might
have an array of several promises but
once one of them succeeds it’s going to
call it’s going to execute whatever you
pass to the then function so they call
back to you pass in there it’s going to
execute once one of the promises is
resolved so that’s basically it for
promises so I hope you enjoyed the video
and we’re gonna continue with generators
in the next one so I hope to see you there bye

Please follow and like us: