JavaScript is a single-threaded language, meaning it can only execute one task at a time. However, we often encounter scenarios where we need to perform tasks that take time, such as fetching data from a server or reading files. These tasks are known as asynchronous operations.
In the past, dealing with asynchronous operations was challenging and resulted in complex callback structures. Fortunately, JavaScript introduced Promises and Async/Await to simplify asynchronous code execution.
Promises represent the eventual result of an asynchronous operation. They have three states: pending, fulfilled, and rejected.
Here's a basic example:
const promise = new Promise((resolve, reject) => {
// Simulate an asynchronous operation
setTimeout(() => {
resolve('Data fetched successfully');
}, 2000);
});
promise.then(data => {
console.log(data); // Outputs: "Data fetched successfully"
})
.catch(error => {
console.error(error);
});
This code creates a promise that resolves after 2 seconds with the message "Data fetched successfully". The .then()
method handles the resolved promise, while .catch()
handles errors.
Async/Await provides a more readable syntax for working with Promises. The async
keyword marks a function as asynchronous, and await
pauses execution until a Promise resolves.
Here's an example:
async function fetchData() {
try {
const response = await fetch('https://api.example.com/data');
const data = await response.json();
return data;
} catch (error) {
console.error(error);
}
}
fetchData().then(data => {
console.log(data);
});
This code uses async/await
to fetch data from an API. The code waits for the fetch request to complete and then parses the response as JSON.
.catch()
and try...catch
blocks.Promises and Async/Await are essential tools for managing asynchronous operations in JavaScript. They offer a more elegant and intuitive approach to dealing with asynchronous code, leading to cleaner and more readable code.