2024-06-07 . 1 min(s)
JavaScript is a single-threaded language, which means it executes code sequentially. However, modern web applications often must perform multiple tasks simultaneously, such as fetching data from an API while allowing the user to interact with the UI. This is where asynchronous JavaScript comes into play.
A Promise is an object that represents the eventual completion (or failure) of an asynchronous operation and its resulting value.
Example:
const fetchData = () => {
return new Promise((resolve, reject) => {
setTimeout(() => {
const data = { message: 'Hello, World!' };
resolve(data);
}, 2000);
});
};
fetchData()
.then(response => {
console.log(response.message); // Output: Hello, World!
})
.catch(error => {
console.error(error);
});
Async/await is syntactic sugar built on top of promises, making asynchronous code easier to read and write.
Example:
const fetchData = () => {
return new Promise((resolve, reject) => {
setTimeout(() => {
const data = { message: 'Hello, World!' };
resolve(data);
}, 2000);
});
};
const fetchDataAsync = async () => {
try {
const response = await fetchData();
console.log(response.message); // Output: Hello, World!
} catch (error) {
console.error(error);
}
};
fetchDataAsync();
Async/await allows you to write asynchronous code that looks synchronous, making it easier to understand and maintain.