Introduction to JavaScript Promises

promise

By Joy Warugu

Javascript is a web development language that is very dynamic and interesting to try keep up with. It has a large community support and hence many new, more efficient ways to solve problems come up almost everyday. Promises, are a relatively new tech in the JS world of asynchrony (don’t worry I explain what asynchronous programming is in the next section). I’m hoping this article will get you guys excited about learning and using promises regularly. If you are new to programming and thinking of learning Javascript, make sure to bookmark this article it should come in handy later!!

Asynchronous vs Synchronous programming

Before, we jump into the deep-end (which is promises) let’s start with a short background. Most likely you’ve have heard of synchronous/asynchronous code. If you haven’t here’s a pretty layman explanation:

Synchronous code: Waits for the code to finish executing before moving on to the next block of code.
Asynchronous code: Can move to other parts of the code before the current block/line is finished.

Let’s say we have a program that executes many tasks and one of those tasks was reading a file. Reading files usually takes quite sometime. If we used synchronous code what would happen is that, during the program execution when the compiler got to reading the file all other parts of the program get blocked waiting for the file to be read and only after the completion of the read is when the program execution may continue. This is so unbelievably inefficient. The better implementation would be asynchronous code which allows other parts of the program to be executing as the file is being read.

So, Javascript is inherently asynchronous. There are a number of ways to implement asynchronicity in Javascript; callbacks, promises, generators and async/await functions. We’ll just focus on promises and maybe mention something about callbacks.

Why Promises?

Why promises? Promises allow one to organise async code in a way that makes sense i.e in a top-down manner. This explanation probably would mostly resonate with people who’ve used callbacks before. With callbacks if you tried writing code in a way that is synchronous (in a linear manner) it will lead to code that is unreadable and that does not execute as expected. Also, known as ‘Callback Hell’ this article here, will be helpful in explaining further what that is.
Also, promises handle more types of errors due to the encouraged use of the familiar try/catch style error handling.

What are Promises?
A promise represents an operation that hasn’t completed yet but is expected to complete in the future.

 

Screen Shot 2017-02-24 at 12.16.18 PM

Fundamental promise principles

A promise at a particular instance can only be in one of three states. These states are:

  1. Resolve – This is when the promise gets the value it expected.
  2. Reject – In case of an error the promise is said to be rejected.
  3. Pending – A promise is said to be pending when it does not yet contain its final value or has not yet reported an error value.

When a promise enters the rejected or resolved state it cannot transition to another state. Let’s see an example of a promise in code:

var isJimmy = false;

var replyText = new Promise(function(resolve, reject) {
 if (isJimmy) {
  var reply = “Answer text immediately”;
  resolve(reply);
 } else {
  var reason = new Error(“Not in the mood to text back”);
  reject(reason)
 }
})

 

The above is a pretty basic promise implementation.

  • We create a new promise that we name replyText.
  • We give a condition that when isJimmy is true then we consider the promise resolved
  • We also specify that if isJimmy is false then the promise is in the reject state.

We interact with promises through its .then and .catch method. The .then method receives the promises eventual value, in the case of success. The .catch method receives an error value, in case of failure. Taking the replyText example we have, consuming this promise would be as easy as this:

replyText
.then(function(response) {
  console.log(response);
  // output: “Answer text immediately”
}).catch (function(err) {
  console.log(err.message);
  // output: “Not in the mood to text back”
})

What happens is:

    • We call the promise replyText.
    • After the call, we usually want to take an action after the promise resolves or rejects.
    • We use .then and .catch to specify what actions to take in case of failure or success.
    • We pass a function into .then that takes an argument response. The argument response is the return of the resolved promise. So, in our case it is reply. The action we have specified is to log the return of the resolved promise therefore our output becomes; “Answer text immediately”
    • We also pass a function into .catch that takes an argument err. This argument takes the return of a rejected promise. Therefore, it takes in the error object we created in our promise, var reason = new Error(“Not in the mood to text back”) .  new Error creates an error object with a key property message that contains the string we passed into it. The action we have specified is to log the message, so our output becomes; “Not in the mood to text back”

In conclusion, when we call the promise if it executes successfully the .then method is called and we get back “Answer text immediately” otherwise if the promise fails we get back, “Not in the mood to text back”.

This is a pretty basic example case used to showcase how to implement promises. Normally, we’d use this exact implementation to allow us to perform pretty awesome and powerful operations on our code. Like, say for example, you wanted to request for a resource from a server (this operation might take some time). You could make the request a promise and specify the success and failure conditions for this request. Then consume the promise by using .then and .catch to specify actions to take in case of success/failure. Doing this allows you to have code that executes much faster than if you had to wait for the server to reply before you can do anything else.
That’s it!! Go discover more (e.g. chaining promises), try them out and halla (@kare_joy) if you have questions or comments. Hope I didn’t bore you a whole lot!!

You may also like

4 Comments

  1. Hi, which books would you recommend a novice programmer to use as far as javascript is concerned. I have been coding in python for about an year now. A few django projects to my name. My Javascript learning has been on freecodecamp so far solving the algorithm challenge.

    1. Hey Kevin, when I started learning JS I used so many resources. I love MEAN Machine (samples.leanpub.com/mean-machine-sample.pdf).
      These are cool for learning fundamental concepts of JS https://github.com/getify/You-Dont-Know-JS.
      Right now I have an app on my phone thats cool its called “enki”.
      I find its best to do a mini-project when learning. scotch.io has some of the best tutorials you can go browse through those.

      1. Thanks Joy much appreciate. You don’t know JS has bee recommended to me before. I should delve into it soon. As well as the other new resources.

  2. Hi…nice tutorial. I love the “promise” concept. I’m quite good in Java but I’m new to Javascript. I hope to enjoy learning it.

Leave a Reply

Your email address will not be published. Required fields are marked *