JavaScript promises are somewhat similar to real-life commitments as they give assurance to do something in the future but without any guarantee of its accomplishment.
For example - A friend promising to go on a trip with you.
There are three states for such a promise:
- Pending: The state of uncertainty after a promise has been made.
- Fulfilled: The promise is kept. That means the friend goes on the trip with you.
- Rejected: The promise is not kept. That means the friend does not go on the trip with you.
What is a JavaScript Promise?
Promises in JavaScript act as a sit-in for a value that is due to become available in the future. JavaScript often gets labeled as a synchronous language. However, usage of callbacks can incorporate asynchronicity. Promises provide an alternative course without getting stuck with the callbacks.
Using JavaScript promises involves two steps, i.e., creating a promise and consuming it afterward.
Creating a JavaScript Promise
Following is the general format to create a promise in JavaScript.
new Promise ( /* executor */ function( resolve, reject) {……………} );
Promise is a constructor here. It takes the executor function with resolve and reject as its parameters.
As discussed earlier, JavaScript promises to provide an efficient way to deal with asynchronous events. If the asynchronous event completes successfully, the resolve function is called. However, if it fails due to some reason, which means the promise is not kept. In such a situation, the reject function is called.
Code:
let tripPromise = true
let goToTrip = new Promise(function( resolve, reject) {
if (tripPromise) {
resolve(“Yes, We went for the trip.”);
} else {
reject(“No. We did not go.”);
}
})
Snippet:
The logic behind the code is quite simple. The promise checks the tripPromise variable for its state. If it evaluates to true, resolve callback is called and the promise stands fulfilled. Otherwise, the reject callback gets called. The promise stands unfulfilled in this scenario.
We have set the tripPromise to true in our code. Thus, the promise gets resolved at the end of the execution. Change tripPromise to false to execute the reject callback.
Console.log() function can be used to log the status of the promise as it executes.
Consuming a JavaScript Promise
To consume a JavaScript promise, we need to call it.
The first step is to create the promise.
Var goToTrip = …. // Create the promise here.
Code:
var areWeGoing = function () {
goToTrip
.then( function (fulfilled) {
console.log( fulfilled);
} )
.catch( function (error) {
console.log( error.message);
});
}
areWeGoing();
Snippet:
Result:
As tripPromise is set to true
As tripPromise is set to false
Methods of the Promises Object
Promises in JavaScript are implemented as Objects, representing resolution or rejection of an asynchronous event.
Promises object supports two types of methods – Static and Prototype methods. While static methods are applied directly to the promise object, prototype methods need individual object instances to function as expected.
If a promise returns another promise, it is called chaining of promises. Both static and prototype methods come with the capability to chain promises.
Prototype Methods
As already stated, prototype methods function with the instances of the Promise object. There are three such methods, and they execute as per the state of the promise.
- Promise.prototype.catch ( onRejected)
- Promise.prototype.then (onFulfilled, onRejected)
- Promise.prototype.finally (onFinally)
If chaining is required, .then and .catch methods can return a promise. .finally remains optional and always gets executed after the associated promise has been settled (either resolved or rejected).
Code:
let tripPromise = true
let goToTrip = new Promise(function( resolve, reject) {
if (tripPromise) {
resolve(“Yes, We went for the trip.”);
} else {
reject(“No. We did not go.”);
}
});
goToTrip.then ( function () {
console.log (“ It was a great trip.”);
});
goToTrip.catch ( function () {
console.log (“ He didn’t show up. Trip was cancelled.”);
});
goToTrip.finally ( function () {
console.log ( “ No matter what, he is an amazing friend.”);
});
Snippet:
Result:
When tripPromise is set to true
When tripPromise is set to false
Static Methods
Similar to prototype methods, static methods can as well be used for chaining promises.
There are four such methods.
- Promise.reject (reason)
- Promise.resolve (value)
- Promise.then()
- Promise.catch()
For example, Promise.reject() helps us create a rejected promise.
Code:
var goToTrip = Promise.reject('No. We did not go.');
goToTrip.then ( function() {
console.log(' It was a great trip.');
});
goToTrip.catch( function() {
console.log(' He did not show up. Trip was cancelled.');
});
Snippet:
Result:
- Promise.resolve() helps us create a fulfilled promise.
Code:
var goToTrip = Promise.resolve('Yes, we went for the trip.');
goToTrip.then ( function() {
console.log(' It was a great trip.');
});
goToTrip.catch( function() {
console.log(' He did not show up. Trip was cancelled.');
});
Snippet:
Result:
Signup Today - https://bit.ly/344Ai4a