// Basic Promise Example: Resolving a value after a delay
function myPromise(delay, value) {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(value); // Resolve with the provided value
}, delay);
});
}
// Example usage:
myPromise(2000, "Hello from myPromise!")
.then(result => {
console.log(result); // Output after 2 seconds: "Hello from myPromise!"
})
.catch(error => {
console.error(error); // This won't execute in this example
});
// More Robust Example: Handling potential errors
function myPromiseWithRejection(delay, value, shouldReject) {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (shouldReject) {
reject("An error occurred!"); // Reject with an error message
} else {
resolve(value); // Resolve with the value
}
}, delay);
});
}
// Example usage demonstrating rejection:
myPromiseWithRejection(1000, "Success!", true)
.then(result => {
console.log(result); // This won't execute
})
.catch(error => {
console.error(error); // Output after 1 second: "An error occurred!"
});
// Example usage demonstrating resolution:
myPromiseWithRejection(1000, "Success!", false)
.then(result => {
console.log(result); // Output after 1 second: "Success!"
})
.catch(error => {
console.error(error); // This won't execute
});
// Example using a real-world scenario (e.g., fetching data):
function fetchData(url) {
return new Promise((resolve, reject) => {
fetch(url)
.then(response => {
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`); // Reject if HTTP error
}
return response.json(); // Parse JSON response
})
.then(data => {
resolve(data); // Resolve with the parsed data
})
.catch(error => {
reject(error); // Reject if any error occurs during fetch or parsing
});
});
}
// Example usage:
fetchData("https://api.example.com/data") // Replace with a real API endpoint
.then(data => {
console.log(data); // Process the fetched data
})
.catch(error => {
console.error("Error fetching data:", error); // Handle errors
});
These examples demonstrate how to create and use promises in JavaScript, including handling success (resolve) and failure (reject) cases, as well as integrating with asynchronous operations like fetch
. Remember to replace "https://api.example.com/data"
with a valid API endpoint for the fetchData
example to work correctly. I've provided progressively more complex examples to help you understand the core concepts and how to apply them in practical scenarios.