What Are Promises in JavaScript
JavaScript example using .then() and .catch() to handle promise result and errors
As web applications grow more complex, developers need efficient ways to handle asynchronous operations like data fetching, event handling, and timers. JavaScript originally relied on callbacks for this purpose, but as the complexity increased, callbacks often led to unmanageable code structures known as "callback hell."
To solve this, Promises were introduced in ES6 (ECMAScript 2015) as a cleaner and more powerful alternative. Promises make asynchronous code more readable, maintainable, and easier to debug.
A Promise is an object representing the eventual completion (or failure) of an asynchronous operation and its resulting value. Promises help you write cleaner asynchronous code, avoiding deeply nested callbacks (callback hell).
A Promise is an object representing the eventual completion (or failure) of an asynchronous operation and its resulting value. Promises help you write cleaner asynchronous code, avoiding deeply nested callbacks (callback hell).
let promise = new Promise(
function(resolve, reject){ // asynchronous task
if (/* success */)
{ resolve("Success!"); }
else { reject("Error!"); } });
** and **
:promise .then(function(result)
{ console.log(result); // "Success!"
}) .catch(function(error) {
console.error(error); // "Error!"
});
function fetchData(callback) {
setTimeout(() => { callback("Data loaded"); }, 1000);
}
fetchData(function(data) { console.log(data); });
function fetchData() {
return new Promise((resolve) => {
setTimeout(() => { resolve("Data loaded"); }, 1000);
}); }
fetchData().then((data) => {
console.log(data); });
Avoid callback nesting (callback hell)
Chain multiple asynchronous operations
Easier error handling using .catch()
Can be combined with async
/await
for even cleaner code
Promises revolutionized how JavaScript handles asynchronous code by providing a more elegant and manageable syntax than traditional callbacks. They reduce complexity, improve readability, and offer structured error handling. As a foundational feature of modern JavaScript, understanding Promises is essential for any developer working with asynchronous operations.