πΉ Promises in JavaScript
π What is a Promise?
A Promise is an object that represents the eventual completion or failure of an asynchronous operation and its resulting value. Promises provide a cleaner, more manageable alternative to traditional callback-based asynchronous programming.
β Advantages of Promises over Callbacks:
Avoid callback hell (nested callbacks).
Better error handling using
.catch().Support for chaining asynchronous operations using
.then().
π Promise States:
A Promise can be in one of three states:
Pending β The initial state, neither fulfilled nor rejected.
Fulfilled β The operation completed successfully.
Rejected β The operation failed.
π§© Basic Syntax:
jsCopyEditconst promise = new Promise((resolve, reject) => {
// async operation
});
resolve(value)β Called when the async operation succeeds.reject(error)β Called when the async operation fails.
π Example: Promisify setTimeout
π§ Code to Create a Promisified Timeout Function:
jsCopyEditfunction setTimeoutPromisified(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
π‘ Explanation:
setTimeoutPromisifiedreturns a Promise that resolves aftermsmilliseconds.setTimeoutis used internally, but instead of using a callback directly, the resolution is handled viaresolve.
π Using the Promisified Function:
jsCopyEditfunction callback() {
console.log("3 seconds have passed");
}
setTimeoutPromisified(3000).then(callback);
π§ Breakdown:
After 3 seconds, the Promise resolves.
.then(callback)is called, executing thecallbackfunction.
β οΈ Tips:
Always handle possible errors using
.catch()in real-world applications.Promises are chainable, so you can do:
jsCopyEditsetTimeoutPromisified(1000) .then(() => console.log("1 second passed")) .then(() => setTimeoutPromisified(2000)) .then(() => console.log("2 more seconds passed"));