forked from annette-arrigucci/es6
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpromise_example.html
69 lines (60 loc) · 2.13 KB
/
promise_example.html
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<script>
//ES5
var request = new XMLHttpRequest();
//onload and onerror are event handlers
request.onload = function () {
var data = JSON.parse(this.responseText);
//do stuff with data
document.writeln("ES5 way<br>");
document.writeln("Name: " + data.name);
};
request.onerror = function () {
alert('There was a problem with the request');
}
request.open('get', 'https://swapi.co/api/people/1/', true);
request.send();
/*
//ES6
function get(url) {
// Return a new promise.
return new Promise((resolve, reject) => {
// Do the usual XHR stuff
var request = new XMLHttpRequest();
request.open('GET', url);
request.onload = () => {
if (request.status == 200) {
// Resolve the promise with the response text
resolve(request.response);
}
else {
// Otherwise reject with the status text
reject(Error(request.statusText));
}
};
// Handle network errors
request.onerror = () => {
reject(Error("Network Error"));
};
// Make the request
request.send();
});
}
get('https://swapi.co/api/people/2/').then((response) => {
//console.log("Success!", response);
var data = JSON.parse(response);
//do stuff with data
document.writeln("ES6 way using promise<br>");
document.writeln("Name: " + data.name);
}, (error) => {
alert('There was a problem with the request: ' + error);
});*/
</script>
</body>
</html>