Promise in Node
Promises in Node.js work the same as in JavaScript, but understanding how they integrate with Node.js's async nature is important.
Key Concepts
- Handle asynchronous operations
- Better than callbacks
- Chain operations easily
- Error handling with catch
Example 1
then((result) => { console.
log(result); return p2; console.
catch((err) => console.
log(err)); Promise.
all([p1, p2]).
catch((error) => console.
log(error)); Promise.
allSettled([p1, p2]).
then((result) => {.
Code
const p1 = new Promise((resolve, reject) => { setTimeout(() => resolve(1), 1000); }); const p2 = new Promise((resolve, reject) => { setTimeout(() => reject(new Error("P2 failed")), 5000); });
Summary
Understanding promise is essential for mastering node. Practice these examples and experiment with variations to deepen your understanding.
Key Takeaways
- promise is a fundamental concept in node
- Practice with these examples to build confidence
- Experiment with variations to explore edge cases
- Understanding promise will help you in technical interviews