Promises are asynchronous computations that represent operations that are yet to be complete.
Having you here means you know some basic knowledge about javascript & How it works synchronously. If you don't no worries here are some links to
Promise terminology
A promise is a JavaScript object that allows you to make asynchronous(aka async) calls. It produces a value when the async operation completes successfully or produces an error if it doesn't complete.
A promise can be:
- fulfilled - The action relating to the promise succeeded.
- rejected - The action relating to the promise failed.
- pending - Hasn't fulfilled or rejected yet.
- settled - Has fulfilled or rejected.
Although promise implementations follow a standardized behavior, their overall APIs differ. JavaScript promises are similar in API to RSVP.js. Here's how you create a promise:
const promise = new Promise(function(resolve, reject)=>{
// do a thing, possibly async, thenβ¦
if (/* everything turned out fine */) {
resolve("Stuff worked!");
}
else {
reject(Error("It broke"));
}
});
Step 1.
The promise constructor takes one argument, a callback with two parameters, resolve
and reject
. Do something within the callback, perhaps async, then call resolve if everything worked, otherwise call reject.
Step 2.
The resolve method indicates successful completion of the task(fetching water), and the reject method indicates an error(the disaster). You do not implement the resolve/reject method. JavaScript provides it to you. You need to call them from the executor function.
Step 3.
so here an example of resolved promise :
// Creating a promise
let promise = new Promise(function(resolve, reject) {
resolve("resolved"); // resloved on success
});
// Consuming a promise
promise.then((value) => console.log(value)) // resloved
so here as you can see to know what exactly a promise is returning after creating a promise we use .then()
and we can say it as consuming a promise.
Step 4.
so here an example of rejected promise :
// Creating a promise
let promise = new Promise(function(resolve, reject) {
reject("rejected"); // rejected on failure
});
// Consuming a promise
promise.then((value) => console.log(value)) // rejected
here promise is rejected so it logs out rejected on failure
Promise States and Object
The promise object should be capable of informing the consumers when the execution has been started, completed (resolved), or returned with an error (rejected).
A promise object has the following internal properties,
state: This property can have the following values,
pending:
When the execution function starts.fulfilled:
When the promise resolves successfully.rejected:
When the promise rejects.
result: This property can have the following values,
undefined: Initially, when the state value is pending.
value:
When the promise is resolved(value).error:
When the promise is rejected.
A promise that is either resolved or rejected is called settled.
`
`
Handling Promises by the Consumers
The promise object returned by the new Promise constructor has it all. A consumer can use it to know the state(pending, fulfilled, or rejected) and the possible outcomes(value or error) from it.
But hold on. These properties are internal. They are code-inaccessible, but they are inspectable. It means that we will be able to inspect the state and result property values using a debugger tool, but we will not be able to access them directly using the program.
So then? That's where we have three important handler methods, .then(), .catch(), and .finally(). These methods help us create a link between the executor and the consumer when a promise resolves or rejects.
The .then()
Promise Handler
We get a .then() method from every promise. The sole purpose of this method is to let the consumer know about the outcome of a promise. It accepts two functions as arguments, result and error.
promise.then(
(result) => {
console.log(result);
},
(error) => {
console.log(error);
}
);
If you are just interested in the successful outcome, you can chose to pass only one argument,
promise.then(
(result) => {
console.log(result);
}
);
Similarly, if you are interested in only the error, pass null as the value for the first argument.
promise.then(
null,
(error) => {
console.log(error)
}
);
Also note, you can do three very exceptional things inside the .then()
method,
- You can
return
another promise from it. - You can
return
a value including undefined. - You can
throw
an error.
These three points will be the basis of learning the Promise Chain which is a whole new advance topic and will cover it in the future blog.
// 1. Creating a Promise
let promise = new Promise(function(resolve, reject) {
// Pretend a delay of 2 sec to fetch it!
setTimeout(function() {
// Let's resolve the promise
resolve('resolved promise');
}, 2000);
});
// now let us consume promise
const consumePromise = () => {
// The handler function to handle the resolved promise
promise.then(function(result) {
console.log(`Consumed ${result}`);
});
}
// 3. Calling the function
consumePromise();
output // Consumed resolved promise
The .catch()
Promise Handler
You can use this handler method to handle errors (rejections) from promises.As we discussed already, it is a much better syntax to handle the error situation than handling it using the .then() method.
.catch()
helps to handle the failure of API calls and handle errors.Here in catch its takes argument which shows the error by consoling it.
using .catch() to handle errors
// 1. Create the promise
let promise = new Promise(function(resolve, reject) {
reject("rejected") // rejected
}
promise.then((value)=>console.log(value))
.catch((error)=>console.log(error))
The .finally()
Promise Handler
The .finally()
handler method performs cleanups like stopping a loader, closing a live connection, and so on. Irrespective of whether a promise resolves or rejects, the .finally() method will be called.
Here .finally()
takes a callback function as argument
// 1. Create the promise
const isLoading = true;
let promise = new Promise(function(resolve, reject) {
reject("rejected") // rejected
}
promise.then((value)=>console.log(value))
.catch((error)=>console.log(error))
.finally(()=>{
isLoading = false
})
Summary
To Summarize,
- Promise is an important building block for the asynchronous concept in JavaScript.
- You can create a promise using the constructor function.
- The constructor accepts an executor function as an argument and returns a promise object.
- A promise object has two internal properties, state and result. These properties are not code-accessible.
- The consumer of a promise can use the .then(), .catch(), and .finally() methods to handle promises.
Top comments (0)