Promises in JS
Promises are objects used to handle asynchronous operations in JavaScript. They represent a value that may be available now, in the future, or never.
function fetchData() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve('Data fetched successfully!');
}, 2000);
});
}
fetchData()
.then(result => {
console.log(result);
})
.catch(error => {
console.error(error);
});
In the above example, fetchData returns a promise that resolves after 2 seconds. You can use the .then() method to handle the resolved value and the .catch() method to handle errors.
No comments:
Post a Comment