Asynchronous JavaScript (Async/Await)
Async/await is a way to write asynchronous code in a more synchronous manner, making it easier to handle promises. It allows you to write code that appears to be synchronous, but actually runs asynchronously.
function fetchData() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve('Data fetched successfully!');
}, 2000);
});
}
async function getData() {
try {
const result = await fetchData();
console.log(result);
} catch (error) {
console.error(error);
}
}
getData();
In the example above, fetchData simulates an asynchronous operation that resolves after 2 seconds. The getData function uses the await keyword to pause execution until the promise returned by fetchData resolves.
No comments:
Post a Comment