JavaScript Promises Explained for Beginners

In this article we'll explore JavaScript promises in simple and easy way. The best way to know how things work about any topic is to know their need. We'll learn about:
What problem promises solve
Promise states (pending, fulfilled, rejected)
Basic promise lifecycle
Handling success and failure
Promise chaining concept
We use promises to handle an asynchronous operations ...but wait can't we do the work without them ? of course we can and to do that work we used to use callbacks.
let's see an example:
getUser(function(user) {
getPosts(user, function(posts) {
getComments(posts, function(comments) {
console.log(comments);
});
});
});
As you can see from above code, how difficult it is to manage it and understand it. This many callbacks give rise to callback hell. That is where promises come.
Promises solve this by:
Making async code clean & readable
Handling success and errors properly
Allowing chaining instead of nesting
Promises has 3 states:
pending: initial state, neither fulfilled nor rejected.
fulfilled: meaning that the operation was completed successfully.
rejected: meaning that the operation failed.
Promise lifecycle
First a promise is created that starts as pending by default. Then if it resolves to success it gets fulfilled. Otherwise it gets rejected.
const promise = new Promise ((resolve,reject) => {
let success = true;
if(success){
resolve("Task completed")
} else {
reject("Task failed")
}
});
Handling success and failure
To handle success and failure in promises we use .then() and .catch(). To handle success we use .then() whereas to to handle failure we use .catch(), let's see with an example:
promise
.then((result)=> {
console.log(result) // success
})
.catch((error)=> {
console.log(error) // failure
})
Remember -
.then()runs when fulfilled.catch()runs when rejected
Promise chaining concept
Promise chaining concept is really a very powerful concept of JavaScript. Instead of using nesting which makes code hard to read and maintain we use chaining.
getUser()
.then((user) => {
return getPosts(user);
})
.then((posts) => {
return getComments(posts);
})
.then((comments) => {
console.log(comments);
})
.catch((error) => {
console.log(error);
});
Here each .then() returns a new promise, data flow step wise and error gets caught in catch(). As you can see this is much better than the callbacks.
Final Thought
Promises help us write clean code for asynchronous work - which is easy to read, understand and maintain. Promises have 3 states - pending, fulfilled and rejected. And we can use .then() to return many new promises and all errors are caught in .catch() block.



