Promises in Javascript
Promises represent the eventual completion or failure of an asynchronous operation. They're essential for handling async code in JavaScript.
Key Concepts
- Better than callbacks for async operations
- Promise.all for parallel execution
- async/await for cleaner syntax
- Proper error handling with try/catch
Creating a Promise
Async operation.
Code
const promise = new Promise((resolve, reject) => { setTimeout(() => { const success = true; if (success) { resolve("Operation successful!"); } else { reject("Operation failed!"); } }, 1000); }); promise .then(result => console.log(result)) // "Operation successful!" .catch(error => console.error(error));
Promise Chaining
Code
const p1 = new Promise((resolve) => { setTimeout(() => resolve(1), 1000); }); p1 .then(result => { console.log(result); // 1 return result * 2; }) .then(result => { console.log(result); // 2 return result * 3; }) .then(result => { console.log(result); // 6 });
Error Handling
Code
const p2 = new Promise((resolve, reject) => { setTimeout(() => reject(new Error("Something went wrong")), 1000); }); p2 .then(result => console.log(result)) .catch(error => console.error("Error:", error.message)); // "Error: Something went wrong"
Promise.all() - All must succeed
If any promise rejects, all fails.
Code
const promise1 = Promise.resolve(1); const promise2 = Promise.resolve(2); const promise3 = Promise.resolve(3); Promise.all([promise1, promise2, promise3]) .then(results => { console.log(results); // [1, 2, 3] }) .catch(error => { console.error("One promise failed:", error); }); const promise4 = Promise.reject("Error"); Promise.all([promise1, promise2, promise4]) .then(results => console.log(results)) .catch(error => console.error(error)); // "Error"
Promise.allSettled() - Wait for all
{ status: 'fulfilled', value: 1 }, { status: 'rejected', reason: 'Error' }, { status: 'fulfilled', value: 3 }.
Code
const p3 = Promise.resolve(1); const p4 = Promise.reject("Error"); const p5 = Promise.resolve(3); Promise.allSettled([p3, p4, p5]) .then(results => { console.log(results); });
Promise.race() - First to settle
Code
const fast = new Promise(resolve => setTimeout(() => resolve("Fast"), 100)); const slow = new Promise(resolve => setTimeout(() => resolve("Slow"), 1000)); Promise.race([fast, slow]) .then(result => console.log(result)); // "Fast"
Promise.any() - First to fulfill
Code
const reject1 = Promise.reject("Error 1"); const reject2 = Promise.reject("Error 2"); const success = Promise.resolve("Success"); Promise.any([reject1, reject2, success]) .then(result => console.log(result)) // "Success" .catch(errors => console.error(errors));
Converting Callbacks to Promises
Code
function callbackFunction(data, callback) { setTimeout(() => { callback(null, `Processed: ${data}`); }, 1000); } function promisify(fn) { return function(...args) { return new Promise((resolve, reject) => { fn(...args, (error, result) => { if (error) reject(error); else resolve(result); }); }); }; } const promiseFunction = promisify(callbackFunction); promiseFunction("test") .then(result => console.log(result)); // "Processed: test"
Async/Await (ES2017)
Code
async function fetchData() { try { const result = await new Promise(resolve => { setTimeout(() => resolve("Data fetched"), 1000); }); console.log(result); // "Data fetched" return result; } catch (error) { console.error("Error:", error); } } fetchData();
Parallel Execution with Async/Await
Code
async function fetchMultiple() { const [result1, result2, result3] = await Promise.all([ Promise.resolve("Data 1"), Promise.resolve("Data 2"), Promise.resolve("Data 3") ]); console.log(result1, result2, result3); // "Data 1 Data 2 Data 3" } fetchMultiple();
Sequential vs Parallel
Sequential (slow) Total: 2s Parallel (fast) Total: 1s Common Patterns 1.
Timeout wrapper 2.
Retry logic 3.
Delay utility.
Code
async function sequential() { const result1 = await fetchData1(); // Wait 1s const result2 = await fetchData2(); // Wait 1s } async function parallel() { const [result1, result2] = await Promise.all([ fetchData1(), // Both start at same time fetchData2() ]); } function withTimeout(promise, timeout) { return Promise.race([ promise, new Promise((_, reject) => setTimeout(() => reject(new Error("Timeout")), timeout) ) ]); } async function retry(fn, retries = 3) { for (let i = 0; i < retries; i++) { try { return await fn(); } catch (error) { if (i === retries - 1) throw error; } } } const delay = ms => new Promise(resolve => setTimeout(resolve, ms)); async function example() { console.log("Start"); await delay(1000); console.log("After 1 second"); }
Summary
Understanding promises is essential for mastering javascript. Practice these examples and experiment with variations to deepen your understanding.
Key Takeaways
- promises is a fundamental concept in javascript
- Practice with these examples to build confidence
- Experiment with variations to explore edge cases
- Understanding promises will help you in technical interviews