Chapter 7 ■ ServiCeS and Server CommuniCation
It’s a fairly bare-bones implementation of a service, but it does cover the basics of service creation. We will see
these same principles and steps applied again shortly, but first, we will take a brief detour to look at a related aspect of
our upcoming registration form submission task: the Promises API.
Promises
The JavaScript Promises API is an emerging standard, which has been implemented in major browsers. It’s a relatively
deep topic, but fortunately we don’t have to dig very deep in order to start using it. Essentially, a promise represents
a value that may not be available yet, but one that will be resolved at some point in future. This value is usually the
outcome of an asynchronous task such as an Ajax call to a remote server, for instance, the Ajax call we will use to
process our registration form data. Just like those we make to each other and to ourselves, a promise can exist in
different states. To start, a promise is in a pending state. That is to say, a promise has been made, but that’s about it.
At some future point, it will become either a promise that has been kept or a promise that has been broken. In the
Promises API, we refer to the former as a fulfilled promise and the latter as a rejected promise.
■ Note a promise can only succeed or fail once. Furthermore, it cannot switch from fulfilled to rejected or vice versa.
The general idea is that you create callback functions and attach them to the different possible states of a
promise. Figure 7-2 represents the general concept.
Figure 7-2. The role of a promise
The unfinished work represents the back-end processing and network communication that will take place
once the user clicks our Register button. Both of these are processes that will take some time, but they will result in
an outcome of some kind eventually. In the meantime, we have the promise, an object that represents this as yet
unknown value. Furthermore, we have the ability to respond to the states of the promise, using callback functions.