-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwikipedia-example.js
53 lines (42 loc) · 1.47 KB
/
wikipedia-example.js
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
// working example of using the Wikipedia API
async function fetchRelatedArticles(title) {
const url = `https://en.wikipedia.org/api/rest_v1/page/related/${title}`;
try {
const promise = await fetch(url);
const data = await promise.json();
return data;
}
catch (error) {
console.error(error);
}
}
// chaining
async function fetchRelatedArticlesChaining(title) {
const url = `https://en.wikipedia.org/api/rest_v1/page/related/${title}`;
return fetch(url)
.then(promise => promise.json())
.catch(console.error);
}
// exception handling
async function fetchRelatedArticlesException(title) {
const url = `https://en.wikipedia.org/api/rest_v1/page/related/${title}`;
try {
const promise = await fetch(url);
const data = await promise.noMethodLikeThis();
return data;
}
catch (error) {
console.log("Error caught!")
console.error(error);
}
}
(async () => {
// const data = await fetchRelatedArticles('JavaScript');
// console.log(data);
// const data = fetchRelatedArticles('JavaScript');
// console.log(data); // Promise { <pending> }
// const dataChaining = await fetchRelatedArticlesChaining('JavaScript');
// console.log(dataChaining);
// const dataException = await fetchRelatedArticlesException('JavaScript');
// console.log(dataException); // undefined because of the error
})();