async
and await
are powerful features in JavaScript that make working with Promises easier and more readable. They allow you to write asynchronous code that looks and behaves like synchronous code. Here's a quick overview:
async
Function
-
Definition: An
async
function is a function that returns a Promise. It allows you to useawait
within it. - Syntax:
async function myFunction() {
// Your code here
}
await
Keyword
-
Definition: The
await
keyword can only be used inside anasync
function. It pauses the execution of theasync
function and waits for the Promise to resolve or reject. - Syntax:
let result = await somePromise;
Example
Here's a simple example to demonstrate how async
and await
work together:
function fetchData() {
return new Promise((resolve) => {
setTimeout(() => {
resolve('Data fetched');
}, 2000);
});
}
async function getData() {
console.log('Fetching data...');
const data = await fetchData();
console.log(data);
}
getData();
In this example:
-
fetchData
is a function that returns a Promise, which resolves after 2 seconds. -
getData
is anasync
function that usesawait
to wait forfetchData
to resolve. - When
getData
is called, it logs "Fetching data...", waits forfetchData
to resolve, and then logs "Data fetched".
Benefits
-
Readability:
async
/await
makes asynchronous code look more like synchronous code, which can be easier to read and understand. -
Error Handling: You can use
try...catch
blocks withasync
/await
to handle errors more cleanly.
Error Handling Example
async function getData() {
try {
console.log('Fetching data...');
const data = await fetchData();
console.log(data);
} catch (error) {
console.error('Error fetching data:', error);
}
}
getData();
In this example, if fetchData
were to reject, the error would be caught by the catch
block, and "Error fetching data:" would be logged along with the error message.
Thank you for reading!
I hope you found this article helpful and informative. If you enjoyed it or learned something new, feel free to share your thoughts in the comments or connect with me.
If you'd like to support my work and help me create more content like this, consider buying me a coffee. Your support means the world and keeps me motivated!
Thanks again for stopping by! 😊
Top comments (0)