-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathasyncAWait2.js
More file actions
34 lines (29 loc) · 825 Bytes
/
asyncAWait2.js
File metadata and controls
34 lines (29 loc) · 825 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
//async and await in js
const API_URL = "https://jsonplaceholder.typicode.com/todos/1";
async function handleAsync() {
try {
const data = await fetch(API_URL);
const jsonValue = await data.json();
console.log(jsonValue);
}
catch(err) {
console.log("Error is: "+err);
}
}
handleAsync();
async function fetchData(url) {
try {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
const data = await response.json();
console.log("Fetched Data:", data);
return data;
} catch (error) {
console.error("Error fetching data:", error);
}
}
// Example usage
const apiUrl = "https://jsonplaceholder.typicode.com/posts/1";
fetchData(apiUrl);