Creating a Promise
A Promise is created using the Promise
constructor, which takes a single argument, a function called the "executor." The executor function takes two arguments: a resolve function and a reject function. The resolve function is used to fulfill the Promise with a resulting value, while the reject function is used to reject the Promise with a reason.
const promise = new Promise((resolve, reject) => {
// Asynchronous operation
});
Promise States
A Promise can be in one of three states:
Pending: The initial state; neither fulfilled nor rejected.
Fulfilled: The operation completed successfully, and the Promise has a resulting value.
Rejected: The operation failed, and the Promise has a reason for the failure.
promise
.then((result) => {
// Handle the result
})
.catch((error) => {
// Handle the error
});
Declaring Async Functions
To use the async/await syntax, you need to declare a function as asynchronous by adding the async
keyword before the function keyword or the arrow function.
async function fetchData() {
// ...
}
const fetchData = async () => {
// ...
};
Using Await
Inside an async function, you can use the await
keyword to pause the execution of the function until a Promise is fulfilled. The await
keyword can only be used within an async function and will return the resolved value of the Promise.
async function fetchData() {
const response = await fetch('https://api.example.com/data');
const data = await response.json();
console.log(data);
}
Error Handling with Async/Await
Handling errors in async/await functions can be done using the traditional try
and catch
blocks. When an error occurs within the try
block, the execution jumps to the corresponding catch
block, allowing you to handle the error gracefully.
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 fetching data:', error);
}
}
Fetching Data from an API
Using the Fetch API, we can retrieve data from a remote server and display it in our application. With async/await, this process becomes more streamlined and easier to read.
async function fetchData() {
try {
const response = await fetch('https://api.example.com/data');
const data = await response.json();
displayData(data);
} catch (error) {
console.error('Error fetching data:', error);
}
}
function displayData(data) {
// Render data in the UI
}
Promise.all()
Promise.all()
is a useful method that takes an array of Promises and returns a new Promise that is fulfilled with an array of the resolved values, in the same order as the input Promises. This is particularly helpful when you need to perform multiple asynchronous operations concurrently and wait for all of them to complete.
async function fetchMultipleData() {
try {
const urls = ['https://api.example.com/data1', 'https://api.example.com/data2'];
const requests = urls.map((url) => fetch(url));
const responses = await Promise.all(requests);
const data = await Promise.all(responses.map((response) => response.json()));
console.log(data);
} catch (error) {
console.error('Error fetching multiple data:', error);
}
}