JavaScript Promises basics: We promise you Promises

What are JavaScript Promises?

Today I want to talk about Promises in JavaScript. The MDN docs say: “The Promise object is used for deferred and asynchronous computations. A Promise represents an operation that hasn’t completed yet, but is expected in the future.” In one article I read the Promise was described as a “Future Object”, a phrase which goes a long way to explaining its purpose. Okay, so a Promise is an object, but what else? Firstly, you need to know that ES6 finally includes Promises, no additional libraries required. Secondly, Promises give us the opportunity to write asynchronous code in a synchronous style that makes our code intelligible and easy to manipulate. Also, a Promise can be in one of three different states: pending, fulfilled or rejected. Personally, I mostly use Promises for work involving servers.

How do Promises work?

A promise represents the eventual result of an asynchronous operation, so after we’ve created a Promise we can use it for either successful handler operations or failed handler operations depending on the result. Once we’ve created a Promise it has a ‘pending’ state. But when we’ve finished doing something, eg. downloading some information from the server, we can change the state of the Promise to either ‘fulfilled’ or ‘rejected’ and pass the result in it. Then we can use Promise’s ‘then’ method to achieve the job that we want to be done after downloading this information from the server.

In general, promises inside a project look like this: promise.then(onFulfilled, onRejected);. So, functions inside ‘then()’ will be called asynchronously. We can even call another Promise after the first Promise’s success (or failure). Better practice though would be to use ‘catch’. When we do, promise.then(onFulfilled, onRejected); becomes this: promise.then(onFulfilled).catch(onRejected);  in this way catch is used to handle errors from onFulfilled. In most cases then, use of catch is recommended. The real power of Promises becomes visible when we have a lot of asynchronous actions.

Overview

So, the three states of a Promise can be explain in this way:
– Pending – initial state, not fulfilled or rejected; until a Promise is fulfilled or rejected it remains in pending state
– Fulfilled – meaning that the operation completed successfully
– Rejected – meaning that the operation completed with failure
The aforementioned Mozilla Developer Network documentation provides the following graphic representation:

Screen Shot 2015 12 01 at 12.00.11

We can see that here Promise’s methods ‘then’ (and ‘catch’) return another Promise.

Example time

Let’s look at how to create a simple Promise:

Here is a real life example of how I used it (with AngularJS):

Enjoy implementing Promises in your own code and exploring them further! Share your own Promises tips in the comments below.

P.S. For a more detailed overview of Promises, I found this article really helpful.