Async/Await
In JavaScript, asynchronous operations are a common part of web development, such as making API calls or reading/writing files. Traditionally, asynchronous operations in JavaScript are handled using promises or callback functions.
With the introduction of ES6+, the async
and await
keywords provide a more elegant and synchronous-like way to write asynchronous code. async
is used to define a function that returns a promise, and await
is used to pause the execution of the function until a promise is resolved.
Here's an example of using async/await
to fetch data from an API:
JAVASCRIPT
1// Replace the following function with your own asynchronous code
2async function fetchData() {
3 try {
4 const response = await fetch('https://api.example.com/data');
5 const data = await response.json();
6 return data;
7 } catch (error) {
8 console.error('Error occurred:', error);
9 throw error;
10 }
11}
12
13// Call the fetchData function
14fetchData()
15 .then(data => {
16 console.log('Received data:', data);
17 })
18 .catch(error => {
19 console.error('Error occurred:', error);
20 });
xxxxxxxxxx
20
// Replace the following function with your own asynchronous code
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 occurred:', error);
throw error;
}
}
// Call the fetchData function
fetchData()
.then(data => {
console.log('Received data:', data);
})
.catch(error => {
console.error('Error occurred:', error);
});
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment