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.
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:
We can see that here Promise’s methods ‘then’ (and ‘catch’) return another Promise.
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.