JavaScript Promises
A promise in a programming language might
seem like an odd concept, but it is not much different from a promise in real
life. Let’s say you make a promise to your dog that
you will take him/her out. You then have to wait for your dog to respond,
hence, your promise is pending on your dog’s response;
he/she might be taking a nap and may not want to go, so they would then reject
your promise and the operation of walking your dog has failed, but if we’re being honest with ourselves, more often than not, your dog
is never going to turn down the opportunity to go out for a walk, in which case
you fulfill the operation of walking your dog successfully.
In a similar way, a promise in
JavaScript will only ever be in one of three states: pending, fulfilled, or
rejected. Assuming that your promise is no longer pending and has received a response,
the promise would then be either fulfilled with a value or rejected with an
error. If your promise was fulfilled, then it would return a then method
with a value that you could use by attaching a handler to the then method. The
handler is just a function that gets called by the then method, let’s give ours the name onFulfillment. An important thing
to note is that our handler function is asynchronous, which means
that it does not necessarily execute in sequential order like a typical synchronous
program. Instead, it executes only when the promise is fulfilled and returns a then
method. That said, inside of our handler, we are free to return another promise
and repeat this process, essentially creating a chain of then methods.
If at any point however, something goes wrong and our promise is rejected with
an error, then the promise would return a catch method with an error
that we could display by using it in a handler function (let’s call this handler function onRejection) in an
identical way that a handler of the then method would work. The last
step of a promise ends in a final then or catch method.
Here is a very
useful diagram that illustrates what we discussed:
Admittedly, that may
have sounded somewhat complicated and convoluted, but I encourage you to try to
relate JavaScript promises to promises in real life and find similarities. This
should allow you to think about this programming concept more intuitively. There
is a lot more to discuss about promises in JavaScript, as this article was more
conceptual and less practical. However, this should get you on the right track,
and implementing promises in JavaScript should be a lot easier for you to do if
you understand these foundational concepts well.
Thanks for reading!
Comments
Post a Comment