Intro
When working with async code in javascript you sometimes need to wait for the code to return data before further processing of data. For example: reading a file takes some times or fetching data from the server can take time and since this is async task it gets delegated. However we need this data before we can process and do anything further in our code. This is where promises can be super helpful.
What is a Promise?
Before promises were introduced, managing asynchronous operations was done using callbacks.
Callbacks are functions that are passed as arguments to another function and are executed later, once the asynchronous operation is complete.
However, as programs grew in complexity, managing callbacks became challenging, leading to what's often referred to as "callback hell" or "pyramid of doom."
This is a situation where nested callbacks make the code hard to read and maintain.
Promises were introduced to address these issues and provide a better/cleaner way to handle asynchronous operations.
So what the heck is a Promise? well, a promise is an object representing the eventual completion or failure of an async operation and its resulting value.
In short if an async task is completed with success it returns a resolve object with the data and if the task fails it returns a reject object with an error. Promise ensures that once the operation is completed, you can do anything you wanted depending on the completion or failure of the operation.
States of a promise
A Promise has three states:
pending: Promise is pending and its neither resolved nor rejected.
resolved: Once promise is resolved it returns data to
then()
rejected: Once promise is rejected the error is returned to
catch()
A basic example of a promise used:
// Creating a promise
let myPromise = new Promise((resolve, reject) => {
// Simulating async operation using setTimeout
setTimeout(() => {
let success = true;
if (success) {
resolve("Data fetched successfully");
} else {
reject("Error fetching data");
}
}, 2000);
});
This piece of code means a new promise is created which does an async operation such as setTimeout()
and once its completed it either resolves
the promise which means success or it gets reject
with an error.
Once created a promise you can consume that promise.
// Consuming the promise
myPromise
.then((result) => {
console.log(result);
})
.catch((error) => {
console.error(error);
})
//default one, gets executed no matter resolve or reject
.finally(() => {});
If the promise is resolved
then it is returned to .then()
method of that promise, if promise is rejected
then it gets returned to .catch()
method.
In both the cases, you can do a task after the promise is completed.
How to handle data returned by a promise?
This can be done with the help of chaining of then() and catch()
Once the data is returned from the resolve you can get that data in then()
method and then return it into a new then
chain and then you can use that data and the error is caught by catch()
method.
const promise = new Promise((resolve, reject) => {
setTimeout(() => {}
const error = false;
console.log("Async task completed!");
//data returned with resolve
if(error === false) resolve([1,2,3]);
, 1000);
});
//handling data with chaining of then() and catch()
promise.then((data) => {
return response;
})
.then((data) => {
console.log(data.splice(0, 1));
})
.catch((err) => {
console.log(err);
})
Conclusion
Promises are just a type of syntactical sugar which makes async programming easier to handle in javascript.