Welcome to our deep dive into JavaScript Promises! In this lesson, we'll learn about Promises, their importance, and various Promise methods that will help you write cleaner, more manageable asynchronous code. Let's get started!
Promises are a JavaScript object representing the eventual completion or failure of an asynchronous operation. They provide a way to handle asynchronous operations in a more organized and manageable manner.
// Example of a Promise
const promise = new Promise((resolve, reject) => {
// asynchronous operation
setTimeout(() => {
if (true) {
resolve('Result');
} else {
reject('Error');
}
}, 2000);
});A Promise can be in one of three states:
resolve function is called.reject function is called.Promises are essential for handling asynchronous operations in JavaScript. They allow for:
.then()The .then() method is used to specify what will happen when a Promise is resolved.
const promise = new Promise((resolve, reject) => {
setTimeout(() => resolve('Result'), 2000);
});
promise.then(result => {
console.log(result); // logs 'Result' after 2 seconds
});.catch()The .catch() method is used to specify what will happen when a Promise is rejected.
const promise = new Promise((resolve, reject) => {
setTimeout(() => reject('Error'), 2000);
});
promise.catch(error => {
console.log(error); // logs 'Error' after 2 seconds
});.all()The .all() method is used to wait for multiple Promises to complete. It returns a new Promise that resolves when all of the input Promises are resolved or rejects if any of them are rejected.
const promise1 = new Promise((resolve, reject) => {
setTimeout(() => resolve('Promise 1'), 1000);
});
const promise2 = new Promise((resolve, reject) => {
setTimeout(() => resolve('Promise 2'), 2000);
});
Promise.all([promise1, promise2]).then(results => {
console.log(results); // logs ['Promise 1', 'Promise 2']
});.race()The .race() method is used to wait for the first of multiple Promises to resolve or reject. It returns a new Promise that resolves or rejects with the result or reason from the first fulfilling Promise.
const promise1 = new Promise((resolve, reject) => {
setTimeout(() => resolve('Promise 1'), 1000);
});
const promise2 = new Promise((resolve, reject) => {
setTimeout(() => reject('Error'), 2000);
});
Promise.race([promise1, promise2]).then(result => {
console.log(result); // logs 'Promise 1' after 1 second
}).catch(error => {
console.log(error); // not executed in this example
});Promises can be used in a variety of applications, from fetching data from APIs to handling user interactions. Here's an example of using Promises to fetch data from an API and display it on a webpage:
const fetchData = (url) => {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.onload = () => {
if (xhr.status === 200) {
resolve(JSON.parse(xhr.responseText));
} else {
reject(`Error: ${xhr.status}`);
}
};
xhr.onerror = () => reject('Network error');
xhr.send();
});
};
fetchData('https://api.example.com/data')
.then(data => {
// do something with the data
console.log(data);
})
.catch(error => {
// handle the error
console.log(error);
});What does the `.then()` method do in a JavaScript Promise?
By now, you should have a good understanding of what JavaScript Promises are and how to use basic and advanced Promise methods. In our next lesson, we'll dive deeper into async/await, another powerful tool for handling asynchronous operations in JavaScript. Until then, keep practicing and happy coding! 😊