JavaScript Promises: Use

This post will take a quick look at promises from the perspective of understanding their use. A later post (at bottom) explains the creation of the promises and provides some sample code.

What is a Promise?

A promise is an object which represents a “promise” to attempt to obtain an object. Passing a function into it’s then() function allows the passing function to specify a function to be called when the promise has either obtained the value or determined that it cannot obtain the value. In promise lingo, this means the promise has “resolved.”

How Do I Know When a Promise Has Resolved?

To perform functionality when a promise resolves we use the then() function.  If the then() function were named for what it does, would be called addResolvedListener(), however it is called then() because of the usage pattern in JavaScript. Which is to say that it is named then() so that you can write the following code and have it read like a story:

The name then() can cause confusion as the Promise itself does not prima facia appear to be an executable. For instance this makes more sense linguistically:

If we were to keep the function then() and then follow a more OO style of naming for the promise itself a promise might work like so:

To fully rename the promise with proper OO naming, to convey the greatest possible clarity, it could be structured like so:

The above rewriting is shown to convey the way a promise might look in an more OO language like Java or C#. You cannot currently add listeners in that way. In fact there is a specification which defines how promises should be defined. It is called the Promises/A+ Specification.

For now however this is the way you will see it used in blogs and in the documentation in GitHub projects:

For those familiar with Java, the Java equivalent is called a Future.  In C# promises are implemented as a Task.

(Next Step: JavaScript Promises Explained Part II).

Categories: JavaScript

Tagged as: , , ,

Leave a Reply

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