Promises in JavaScript are used to handle asynchronous operations. Letβs walk through what they are and test some examples live.
π Basic Promise Example
This promise resolves after 2 seconds:
const promise = new Promise((resolve, reject) => {
setTimeout(() => {
resolve("β
Promise resolved!");
}, 2000);
});
promise.then(result => console.log(result));
β Promise Rejection Example
Hereβs a Promise that rejects when something goes wrong:
const errorPromise = new Promise((resolve, reject) => {
setTimeout(() => {
reject("β Something went wrong");
}, 1500);
});
errorPromise
.then(data => console.log(data))
.catch(error => console.error(error));
π Real Use Case: Fetching Data
Letβs simulate fetching user data:
function fetchUserData() {
return new Promise((resolve) => {
setTimeout(() => {
resolve({ name: "John Doe", age: 30 });
}, 1000);
});
}
fetchUserData().then(user => console.log(user));
β¨ Try modifying the delays or values in the code to understand how Promises behave!