// Asynchronous function to fetch data from an API
async function fetchData() {
// Fetch data from the specified URL
const response = await fetch('https://api.example.com/data');
// Parse the JSON data from the response
const data = await response.json();
// Return the parsed data
return data;
}
// Call the asynchronous function and handle the returned Promise
fetchData().then((data) => {
// Log the retrieved data to the console
console.log(data);
});Asynchronous Fetch in JavaScript using async/await
javascript
Related Posts
More content you might like
Tutorial
javascript
JavaScript in Modern Web Development
JavaScript isn't limited to the browser anymore. It's being used in diverse domains:
- Tools like React Native enable building native apps using JavaScript.
- Example: Facebook's mobile app.
Dec 10, 2024
Read More Tutorial
javascript
AJAX with JavaScript: A Practical Guide
Before the Fetch API, the traditional way to make AJAX requests was using XMLHttpRequest.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>AJAX with XMLHttpRequest</title>
</head>
<body>
<button id="fetchDataBtn">Fetch Data</button>
<div id="dataOutput"></div>
<script>
document.getElementById('fetchDataBtn').addEventListener('click', function() {
var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://jsonplaceholder.typicode.com/posts/1', true);
xhr.onload = function() {
if (this.status === 200) {
var data = JSON.parse(this.responseText);
document.getElementById('dataOutput').innerHTML = `
<h3>${data.title}</h3>
<p>${data.body}</p>
`;
}
};
xhr.onerror = function() {
console.error('Request failed.');
};
xhr.send();
});
</script>
</body>
</html>Sep 18, 2024
Read More Code
javascript
React Custom Hook for API Requests
No preview available for this content.
Aug 12, 2024
Read More Code
javascript json
JavaScript Code Snippet: Fetch and Display Data from an API
No preview available for this content.
Aug 04, 2024
Read MoreDiscussion 0
Please sign in to join the discussion.
No comments yet. Be the first to share your thoughts!