-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.html
More file actions
79 lines (78 loc) · 3.01 KB
/
index.html
File metadata and controls
79 lines (78 loc) · 3.01 KB
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
70
71
72
73
74
75
76
77
78
79
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta
name="viewport"
content="width=device-width, initial-scale=1.0"
/>
<title>Promise基本用法</title>
</head>
<body>
<button id="request">发起请求</button>
<p id="output"></p>
<script type="text/javascript">
const url =
"https://raw.githubusercontent.com/zhixingxiaoke/javascript-asynchronous-programming/main/README.md"
document.getElementById("request").addEventListener("click", () => {
document.getElementById("output").innerText = ""
request(url)
.then((v) => {
document.getElementById("output").innerText = v
return request(url)
})
.then((v) => {
document.getElementById("output").innerText += v
return request(url)
})
.then((v) => {
document.getElementById("output").innerText += v
})
.catch((e) => {
alert(e)
})
// new Promise((resolve, reject) => {
// setTimeout(() => {
// resolve(1)
// }, 1000)
// console.log("running...")
// })
// .then((v) => {
// console.log(`resolve: ${v}`)
// return new Promise((resolve, reject) => {
// resolve(v + 1)
// })
// })
// .then((v) => {
// console.log(`resolve: ${v}`)
// })
// .catch((e) => {
// console.log(`reject: ${e}`)
// })
// .finally(() => {
// console.log("cleanup")
// })
})
function request(url) {
return new Promise((resolve, reject) => {
// 1. 创建 XMLHttpRequest 对象
const httpRequest = new XMLHttpRequest()
// 2. 设置处理服务器响应的回调
httpRequest.onreadystatechange = () => {
if (httpRequest.readyState !== XMLHttpRequest.DONE) {
return
}
if (httpRequest.status == 200) {
resolve(httpRequest.responseText)
} else {
reject(httpRequest.status)
}
}
// 3. 建立连接并发送数据
httpRequest.open("GET", url)
httpRequest.send()
})
}
</script>
</body>
</html>