What are Promises?
Promises are used to handle asynchronous operations in JavaScript. They represent a value that may be available now, in the future, or never.
Creating a Promise
You can create a promise using the Promise constructor. It takes a function with two arguments: resolve and reject.
Example: Creating a Promise
const myPromise = new Promise((resolve, reject) => {
setTimeout(() => {
resolve("Success!");
}, 1000);
});
Handling Promises
Use .then() to handle resolved promises and .catch() to handle rejected promises.
Example: Handling a Promise
myPromise
.then(result => {
console.log(result); // "Success!"
})
.catch(error => {
console.error(error);
});
Chaining Promises
You can chain multiple promises using .then(). Each .then() returns a new promise.
Example: Chaining Promises
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => {
console.log(data);
})
.catch(error => {
console.error(error);
});
Async/Await
Async/await is a modern way to handle promises. It makes asynchronous code look synchronous.
Example: Async/Await
async function fetchData() {
try {
const response = await fetch('https://api.example.com/data');
const data = await response.json();
console.log(data);
} catch (error) {
console.error(error);
}
}
Call for Live Sessions
Want to learn more? Call us at 078 777 0000 to arrange a live session with our experts!