-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathasync-await.js
More file actions
35 lines (29 loc) · 795 Bytes
/
async-await.js
File metadata and controls
35 lines (29 loc) · 795 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
35
const delay = ms => {
return new Promise(r => setTimeout(() => r(), ms));
}
const url = "https://jsonplaceholder.typicode.com/todos";
// This is function with class promise.
function fetchByUrl() {
return delay(3000)
.then(() => fetch(url))
.then(response => response.json())
}
fetchByUrl()
.then(data => {
console.log(`Data from url: ${data}`);
})
.catch(error => console.error(error));
// This is function with async/await.
async function fetchByUrlAsync() {
try {
await delay(3000);
const response = await fetch(url);
const data = response.json();
console.log(`Data from url: ${data}`);
} catch (error) {
console.error(error);
} finally {
console.log("Finally.")
}
}
fetchByUrlAsync();