Promises In Javascript
Introduction
In the world of JavaScript, asynchronicity reigns supreme. Many operations, such as network requests and file I/O, are inherently asynchronous. In the past, handling these asynchronous operations could be a daunting task, often leading to callback hell and hard-to-maintain code. However, the introduction of Promises has changed the game, making it easier than ever to manage asynchronous operations. In this article, we will dive deep into Promise operations in JavaScript, mastering this powerful tool.
What Are Promises?
Before we get into the Promise operations, let’s start with the basics. A Promise is an object that represents a value that might not be available yet but will be at some point in the future. Promises are used to handle asynchronous operations, such as fetching data from an API, reading a file, or making a database query.
A Promise can be in one of three states:
- Pending: The initial state, representing the promise’s state before it’s resolved or rejected.
- Fulfilled: The state indicating that the asynchronous operation was completed successfully, resulting in a resolved promise.
- Rejected: The state indicating that the asynchronous operation encountered an error or was unsuccessful, leading to a rejected promise.
Creating Promises
You can create a Promise using the Promise constructor, which takes a single function as an argument. This function, often referred to as the “executor,” has two parameters: resolve and reject. Inside this function, you perform the asynchronous operation and call resolve when it's successful or reject when an error occurs.
Consuming Promises
Once you’ve created a Promise, you need to consume it. Promises provide two methods for handling the resolved or rejected value: then and catch.
The then method is used to specify what should happen when the promise is fulfilled (resolved). It takes two optional callback functions: one for success and another for failure (rejection) i.e catch.
Get Vidya Jayagouda’s stories in your inbox
Join Medium for free to get updates from this writer.
Let’s see the example:
- In this example will learn how to create a promise and how to consume the promise.
// create a promise
const promiseOne = new Promise( ( resolve, reject ) =>
{
// do the async operation like calling a API , db connections etc
setTimeout( () =>
{
console.log( "Async operation completed" );
// to connect the then and promise we need to call resolve()
resolve();
}, 1000 );
} );
//consume the promise
promiseOne.then( () =>
{
console.log( "Promise executed suscussefuly." );
} ).catch( ( error ) =>
{
console.log( "Promise executed unSuscussefuly." );
} );
// we can create a promise like this also
new Promise( ( resolve, reject ) =>
{
setTimeout( () =>
{
console.log( "Async operation completed" );
// to
resolve();
}, 1000 );
} ).then( () =>
{
console.log( "Promise executed suscussefuly." );
} ).catch( () =>
{
console.log( "Promise executed unSuscussefuly." );
} );
//2. In this example will learn how to create a promise and how to read the data when the resolve function calls in the promise.
// create a promise and consume the promises and learn how to read the data from the resolve
const promiseTwo = new Promise( ( resolve, reject ) =>
{
setTimeout( () =>
{
console.log( "Async operation 2" );
resolve( {
userName: 'Vidya',
role: 'Software Developer',
company: 'Nonstopio Technologies'
} );
}, 1000 );
} );
promiseTwo.then( ( user ) =>
{
console.log( "response", user );
} );3. In this example will learn how to read the error when the promise is rejected.
// lets learn when promise is rejected how to read the error
const promiseFour = new Promise( ( resolve, reject ) =>
{
setTimeout( () =>
{
console.log( "Async operation 4" );
let error = true;
if ( !error )
{
resolve( {
userName: 'Vidya',
role: 'Software Developer',
company: 'Nonstopio Technologies'
} );
} else
{
reject( "Error: Something went wrong" );
}
} );
}, 1000 );
promiseFour.then( ( user ) =>
{
console.log( "response", user );
} ).catch( ( error ) =>
{
console.log( "Caught an Error", error );
} );4. Promise Chaining: Promises become even more powerful when you chain them together. Chaining allows you to sequence multiple asynchronous operations. When one operation is completed, you can start the next one. This results in cleaner and more maintainable code.
Let us learn promise changing from the example.
// lets learn promise chaining and finally block
const promiseFive = new Promise( ( resolve, reject ) =>
{
setTimeout( () =>
{
console.log( "Async operation 5" );
let error = false;
if ( !error )
{
resolve( {
userName: 'Vidya',
role: 'Software Developer',
company: 'Nonstopio Technologies'
} );
} else
{
reject( "Error: Something went wrong" );
}
} );
}, 1000 );
promiseFive.then( ( user ) =>
{
return user?.userName;
} ).then( ( userName ) =>
{
console.log( "User Name: ", userName );
} ).catch( ( error ) =>
{
console.log( "Caught an Error", error );
} ).finally( () =>
{
// this will execute either promise is resolved or rejected
console.log( "The promise is either resolve or rejected" );
} );5. Async and await in Promises
Async/Await makes it easier to write promises. The keyword ‘async’ before a function makes the function return a promise, always. The keyword await is used inside async functions, which makes the program wait until the Promise resolves or is rejected.
let’s learn how the async and await are used in promise with example.
// the promise with async and wait
const promiseSix = new Promise( ( resolve, reject ) =>
{
setTimeout( () =>
{
console.log( "Async Operation 6" );
let error = true;
if ( !error )
{
resolve( {
userName: 'Vidya',
role: 'Software Developer',
company: 'Nonstopio Technologies'
} );
} else
{
reject( "Error: Something went wrong" );
}
}, 1000 );
} );
const consumePromise = async () =>
{
// try catch block is used to handle resolve and to catch the error
try
{
const response = await promiseSix;
console.log( response, "response" );
} catch ( error )
{
console.log( `Error: ${ error }` );
}
};
consumePromise(6. Parallel Promises
There are situations where you need to perform multiple asynchronous operations in parallel and wait for all of them to complete before proceeding. JavaScript provides the Promise.all method for such cases. It takes an array of Promises and returns a new Promise that fulfills with an array of resolved values once all the input Promises have been fulfilled.
// promise all
const promise1 = new Promise( ( resolve, reject ) =>
{
setTimeout( () =>
{
resolve( {
userName: 'Vidya',
gender: 'female'
} );
}, 1000 );
} );
const promise2 = new Promise( ( resolve, reject ) =>
{
setTimeout( () =>
{
let error = false;
if ( !error )
{
resolve( {
hobbies: [ 'reading', 'traveling' ]
} );
} else
{
reject( "promise two rejected" );
}
}, 1000 );
} );
const promise3 = new Promise( ( resolve, reject ) =>
{
setTimeout( () =>
{
let error = false;
if ( !error )
{
resolve( {
role: 'developer',
company: 'Nonstopio'
} );
} else
{
reject( "promise three rejected" );
}
}, 1000 );
} );
Promise.all( [ promise1, promise2, promise3 ] ).then( ( user ) =>
{
console.log( user );
} ).catch( ( error ) =>
{
console.log( `Error: ${ error }` );
} )Conclusion
Promises have revolutionized how we handle asynchronous operations in JavaScript. They provide a clear and elegant way to work with asynchronous code, avoiding callback hell and making our code more readable and maintainable. With chaining and Promise.all, we can easily handle complex asynchronous flows. As you dive deeper into JavaScript development, mastering promises is a fundamental skill that will serve you well in building robust and efficient applications.
Remember that in modern JavaScript, you also have access to async/await, which simplifies working with Promises even further. Promises are a stepping stone to understanding the asynchronous nature of JavaScript, and they remain a valuable tool in your toolkit. So, go ahead, embrace Promises, and unlock the true potential of asynchronous JavaScript development.
Here to make the community stronger by sharing our knowledge. Follow me and my team to stay updated on the latest and greatest in the web & mobile tech world.




![Mastering React Hooks: A Comprehensive Guide to Streamlining Your Component Magic[Part-II]](https://miro.medium.com/v2/resize:fit:1358/format:webp/1*WwahPBaloup2qnIdQoKsJw.png)





