-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathasync和await.html
More file actions
65 lines (63 loc) · 1.98 KB
/
Copy pathasync和await.html
File metadata and controls
65 lines (63 loc) · 1.98 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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>async/await</title>
</head>
<body>
<script>
const main = async () => {
//1.非Promise则返回一个成功的Promise,值为返回值
// return 521;
//2.Promise则返回结果由它来决定
return new Promise((resolve, reject) => {
resolve('ok');
})
//3.抛出错误则返回错误的Promise,值为抛出的值
// throw '错误';
}
console.log(main());
async function dj() {
const p = new Promise((resolve, reject) => {
reject('错误嗷嗷');
})
try{
const res = await p;
console.log(res);
}catch(e) {
console.log(e);
}
}
dj();
//async-await发送ajax请求
function sendAjax() {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.responseType = 'json'; //指定返回结果格式
xhr.open('GET', 'https://ku.qingnian8.com/dataApi/news/navlist.php');
xhr.send();
xhr.onreadystatechange = () => {
if (xhr.readyState === 4) {
if (xhr.status >= 200 && xhr.status < 300) {
resolve(xhr.response);
} else {
reject(xhr.status);
}
}
}
});
}
async function getNews() {
try{
let result = await sendAjax();
console.log(result);
}catch(e) {
console.log(e);
}
}
getNews();
</script>
</body>
</html>