What is async/await in JavaScript
JavaScript example using await to resolve a promise
async/await
in JavaScript?
async
and await
are syntactic sugar introduced in ES2017 (ES8) that make working with Promises easier and more readable. They allow you to write asynchronous code that looks and behaves like synchronous code, making it simpler to understand and maintain.
async
Function?
An async
function always returns a Promise. You can use await
inside it to pause the execution of the function until a Promise resolves or rejects.
async function fetchData() {
// Your asynchronous code here
}
await
Keyword?
The await
keyword pauses the function execution until the Promise resolves. It only works inside an async function. If the Promise is rejected, an error is thrown and can be caught using try...catch
.
function getData() {
return new Promise((resolve) => {
setTimeout(() => resolve("Data received"), 2000);
});
}
async function showData() {
const result = await getData();
console.log(result); // Output: "Data received"
}
showData();
try...catch
async/await
works seamlessly with try...catch
blocks, allowing developers to handle errors in a straightforward and readable way.
async function fetchWithError() {
try {
let result = await fetch('invalid-url');
let data = await result.json();
console.log(data);
} catch (error) {
console.error("Error occurred:", error.message);
}
}
async/await
Cleaner and more readable than chaining .then()/.catch()
Easier debugging and error handling using try...catch
Mimics synchronous code structure, improving comprehension