const fetchData = () => {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve('Data fetched successfully!');
}, 1000);
});
};
fetchData()
.then(response => {
console.log(response); // Output: Data fetched successfully!
return 'Processing data...';
})
.then(processedData => {
console.log(processedData); // Output: Processing data...
return 'Data processing complete!';
})
.then(finalMessage => {
console.log(finalMessage); // Output: Data processing complete!
})
.catch(error => {
console.error(error);
});
Error handling in Promises is straightforward. If an error occurs at any point in the Promise chain, it will be caught by the catch
block.