What is a JavaScript Promise?
Before diving into details, let’s first understand what a JavaScript promise is. A promise represents the eventual completion (or failure) of an asynchronous operation and its resulting value. Think of a promise as a commitment to deliver something in the future.
Real-Life Example: Imagine you order a pizza at a restaurant. The waiter tells you it will take 20-30 minutes. You’ve essentially made a promise to yourself that the pizza will be delivered within that time frame. If the pizza arrives and it tastes good, the promise is fulfilled (resolved). If it doesn’t meet your expectations, the promise is rejected.
How to Use Promises in JavaScript
Here’s a simple example of how to create and use a promise in JavaScript:
let pro = new Promise((resolve, reject) => {
setTimeout(() => {
console.log('Hello, World!');
resolve('Success'); // Resolve the promise with a value
}, 2000);
});
pro.then(result => {
console.log("Promise resolved with:", result);
}).catch(error => {
console.log("Promise rejected with:", error);
});
In this example:
Creating a Promise: new Promise((resolve, reject) => { ... }) creates a new promise.
It takes two arguments: resolve and reject.
Resolving the Promise: After 2 seconds, the promise is resolved with the value
'Success'.
Handling the Promise Result: Use .then() to handle a resolved promise and .catch()
to handle any errors.
Understanding promises is crucial for handling asynchronous operations in
JavaScript. If you found this post helpful, share it with your fellow developers!
If you have any questions about promises or need further clarification, leave a
comment below—I’d be happy to help!