Promises in Javascript
Javascript(JS) has a mechanism called promises and it does exectly samething as we do with our promise.
Introduction
A promise is a object that represents eventual completion (or failure) of asyncronous operations.
Simple defination:
A placeholder for a future value.
Use of Promise:
To execute asyncronous code without blocking javascript's main thread.
- To achieve parallelisiam.
Asyncronous codes like:
- fetch
- timer
- some independent long running code
Initially, when we create a new Promise it gives an object containing status, prototype, result.
const promise = new Promise((resolve, reject)=>{});
console.log(promise);Output
{
Prototype: Promise,
PromiseStatus: 'pending',
PromiseRestult: undefined
}It has three state:
- Pending: Shows the promise not completed execution yet.
- Fullfilled: Shows excution completed successfully.
- Failed: Show Excution failed.
Create a new Promise:
Most common ways to create promise is:
- Promise Constructor:
const user = new Promise((resolve, reject)=>{});- async Function:
async function user(){
// Async operations here.
}Both code chunks are same.
What are resolve and reject ?
These are callback functions use to mark success and failure respectively.
const img = new Prommise((resolve, reject)=>{
try{
// Some heavy calculation
resolve(enhancedImage);
}catch(error){
// If error happens
reject(error.message);
}});
img.then((img)=>{
updateImageInDOM(img);
}).catch((error)=>{
console.error(error);
});Error handling in Promise:
.catch() method is used to catch any error from promise. like in the above example.
Then comes .finally() , It runs reagardless of failure or success. We can use finally when we need to do something on completion either it's success or failure.
fetch('https://jsonplaceholder.typicode.com/users')
.then((data)=>
data.json()
).catch((error)=>{
console.error(error.message);
}).finally(notify)Usefull Promise Utilities:
Promise.all():Gets array of promises and waits for all to complete if anyone fails, It complete failure.
Best for Initial load to fetch all essential data.
Promise.allSettled():Gets array of promises and returns result of each.
Best for bulk async operations.
Promise.race():Gets array of promises and returns first settled one.
Best for multiplayer quick quiz scenario.
Promise.any():Gets array of promises and returns the first fullfilled promise.
Best for multiplayer quick quiz scenario.
Remember: .then() callback goes into Microtask Queue, Because Promise callbacks never execute synchronously.Promise CheetSheet for quick revision.
👋 Thanks for Reading
If this article helped you understand Different Rendering Strategies in Next.js, consider sharing it with fellow developers.
Connect With Me
- LinkedIn: https://www.linkedin.com/in/devankesh/
Have Questions?
Drop your thoughts in the comments. I'd love to discuss ideas, answer questions, and learn from your perspective.
Follow for More
I write about:
- JavaScript
- TypeScript
- React
- Frontend Architecture
- Web Performance
- Software Engineering