Promises in Javascript : Basic Class You Missed [Part :01 ]

The Deca Dose
3 min readJul 16, 2023

--

Photo by alise storsul on Unsplash

Introduction:
In the world of JavaScript, asynchronous operations play a vital role in creating responsive and efficient web applications. One key tool for managing asynchronicity is JavaScript Promises. Understanding promises is crucial for developers looking to harness the power of asynchronous programming. In this article, we will delve into the inner workings of promises, explore their benefits, provide code examples, and discuss practical use cases. So, grab your coding gear and let’s unravel the mysteries of JavaScript Promises!

## Table of Contents:
1. What are JavaScript Promises?
2. Anatomy of a Promise
3. Chaining Promises for Sequential Execution
4. Error Handling with Promises
5. Promises vs. Callbacks
6. Practical Use Cases
7. Conclusion

## 1. What are JavaScript Promises?
JavaScript Promises are objects that represent the eventual completion (or failure) of an asynchronous operation and its resulting value. Promises simplify working with asynchronous code, making it more readable and easier to reason about. Promises can be considered as placeholders for values that might not be immediately available but will be resolved at some point in the future.

## 2. Anatomy of a Promise
A Promise has three states:
- **Pending**: The initial state when the promise is neither fulfilled nor rejected.
- **Fulfilled**: The state when the asynchronous operation is completed successfully, resulting in a value.
- **Rejected**: The state when the asynchronous operation fails, resulting in an error.

Promises have two main methods:
- .then() : Attaches callbacks to handle the fulfillment or rejection of the promise.
- .catch() : Handles errors in case the promise is rejected.


const fetchData = new Promise((resolve, reject) => {
// Asynchronous operation
setTimeout(() => {
const data = ‘Fetched data’;
resolve(data); // Fulfill the promise
}, 2000);
});

fetchData
.then(result => {
console.log(result); // Output: Fetched data
})
.catch(error => {
console.error(error);
});

## 3. Chaining Promises for Sequential Execution
One of the powerful features of promises is the ability to chain them together, allowing sequential execution of asynchronous operations. This ensures that each operation completes before the next one starts, making the code more structured and readable.


fetchData()
.then(data => {
return process(data); // Returns another promise
})
.then(processedData => {
return save(processedData); // Returns another promise
})
.then(() => {
console.log(‘Data saved successfully!’);
})
.catch(error => {
console.error(error);
});

## 4. Error Handling with Promises
Promises provide a convenient way to handle errors by utilizing the `.catch()` method. If any promise in the chain rejects, the error will propagate down to the nearest `.catch()` block. This simplifies error handling and avoids the “callback hell” situation.



fetchData()
.then(data => {
if (!data) {
throw new Error(‘Data not found!’);
}
return process(data);
})
.then(processedData => {
return save(processedData);
})
.then(() => {
console.log(‘Data saved successfully!’);
})
.catch(error => {
console.error(error); // Output: Data not found!
});

## 5. Promises vs. Callbacks
Promises have become the preferred approach for handling asynchronous operations over traditional callbacks due to their cleaner syntax, improved error handling, and support for chaining. Promises offer more readability, maintainability, and are easier to debug.

## 6. Practical Use Cases
Promises find their utility in various scenarios, such as:
- Fetching data from a server using AJAX.
- Handling multiple API requests in parallel and waiting for all of them to complete.
- Loading external resources, like images or scripts, asynchronously.

## Conclusion
JavaScript Promises are a powerful tool for managing asynchronous operations, enabling developers to write clean, structured, and maintainable code. By understanding their inner workings and harnessing their potential, you can build efficient web applications that are more responsive and user-friendly. Embrace promises, unlock the full potential of asynchronous programming, and take your JavaScript skills to new heights!

Remember, JavaScript Promises are your key to unlocking the asynchronous power in the world of web development. Happy coding!

If this article gets 5 followers we will create a full detailed series on javascript promises and its use cases . Our next article will be available soon on use of promises in scalability and concurrency .

Part 2 as promised : https://medium.com/@vikramgyawali57/promises-in-javascript-basic-class-you-missed-part-02-9a842d7cfdb0

*References:
- MDN Web Docs: [Promises](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)
- JavaScript.info: [Promises](https://javascript.info/promise-basics)
- Promises in JavaScript: [A Beginner’s Guide](https://www.freecodecamp.org/news/javascript-promises-explained/)

--

--

The Deca Dose

Get the top and best suggestions for programming , coding and all the techs