
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 aPromise? 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 resolved
- resolved: Once promise is resolved it returns data to
then()
method - rejected: Once promise is rejected the error is returned to
catch()
A basic example of a promise used:
// Creating a promiseletmyPromise=newPromise((resolve,reject)=>{// Simulating async operation using setTimeoutsetTimeout(()=>{letsuccess=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 assetTimeout()
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 promisemyPromise.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 the promise?
This can be done with the help of chaining of then() and catch()
Once the data is returned from theresolve
you can get that data inthen()
method and then return it into a newthen
chain and then you can use that data and the error is caught bycatch()
method.
constpromise=newPromise((resolve,reject)=>{setTimeout(()=>{}consterror=false;console.log("Async task completed!");//data returned with resolveif(error===false)resolve([1,2,3]);,1000);});//handling data with chaining of then() and catch()promise.then((data)=>{returndata;}).then((data)=>{console.log(data.splice(0,1));}).catch((err)=>{console.log(err);})
Top comments(5)

- LocationMaine
- Pronounshe/him
- WorkUI Architect at Bottomline Technologies
- Joined
Nice article! This is a solid introduction to promises.
However, there is an error in your last code example.
// argument "data" and return "response" don't matchpromise.then((data)=>{returnresponse;})
This should either receiveresponse
as the argument, or returndata
. Either way, if it returns the original value the entire.then()
is not necessary.
If you are interested in some more suggestions for working with Promises, I wrote an article calledPromises: Five Tips to Work Smarter

- Email
- LocationIndia
- EducationMaster of Computer Applications
- PronounsHe/They
- WorkTechnical writer (Part-time)
- Joined
Fixed it, thanks for the update! :)

- Email
- LocationIndia
- EducationMaster of Computer Applications
- PronounsHe/They
- WorkTechnical writer (Part-time)
- Joined
Thankyou for reading! :)
For further actions, you may consider blocking this person and/orreporting abuse