Promises are a way to represent values that might be available now, in the future, or never. They provide a clean and structured way to work with asynchronous code, avoiding the issues associated with callbacks in javascript.
A Promise can be in one of three states:
const myPromise = new Promise((resolve, reject) => {
// Asynchronous operation
if (/* operation is successful */) {
resolve(result); // Fulfill the promise with a value
} else {
reject(error); // Reject the promise with a reason (error)
}
});
// Using the Promise
myPromise
.then((result) => {
console.log("Fulfilled:", result);
})
.catch((error) => {
console.error("Rejected:", error);
});
Promises can be chained using the .then()
method, allowing for sequential execution of asynchronous operations.
const firstAsyncOperation = () => {
return new Promise((resolve) => {
setTimeout(() => {
console.log("First operation completed");
resolve(1);
}, 1000);
});
};
const secondAsyncOperation = (value) => {
return new Promise((resolve) => {
setTimeout(() => {
console.log("Second operation completed");
resolve(value + 1);
}, 1000);
});
};
firstAsyncOperation()
.then((result) => secondAsyncOperation(result))
.then((finalResult) => {
console.log("Final result:", finalResult);
})
.catch((error) => {
console.error("Error:", error);
});
Promises use the .catch()
method to handle errors, making it easy to separate error handling from the main flow.
const asyncOperationWithError = () => {
return new Promise((resolve, reject) => {
setTimeout(() => {
const success = Math.random() > 0.5; // Simulating success or failure
if (success) {
resolve("Operation completed successfully");
} else {
reject(new Error("Operation failed"));
}
}, 1000);
});
};
asyncOperationWithError()
.then((result) => {
console.log("Success:", result);
})
.catch((error) => {
console.error("Error:", error.message);
});
Promises can be used to convert callback-based APIs into a promise-based style, making code more readable and manageable.
const readFilePromise = (path) => {
return new Promise((resolve, reject) => {
readFile(path, 'utf8', (err, data) => {
if (err) {
reject(err);
} else {
resolve(data);
}
});
});
};
readFilePromise('/path/to/file.txt')
.then((content) => {
console.log('File content:', content);
})
.catch((error) => {
console.error('Error reading file:', error.message);
});
Promises provide a cleaner and more structured way to handle asynchronous operations compared to traditional callbacks. They simplify error handling, allow for sequential chaining of operations, and make it easier to reason about asynchronous code.
Encapsulation and abstraction are two pillars of object-oriented programming (OOP) that play a vital role…
Polymorphism is a fundamental concept in object-oriented programming (OOP) that allows objects to take on…
Inheritance is a cornerstone of object-oriented programming (OOP) and one of its most powerful features.…
In the world of C# and object-oriented programming (OOP), classes and objects form the backbone…
In modern C# programming, working with data collections is a common task. Understanding how to…
Exception handling is a critical part of writing robust and maintainable C# applications. It allows…