-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpromise.html
More file actions
100 lines (85 loc) · 2.4 KB
/
promise.html
File metadata and controls
100 lines (85 loc) · 2.4 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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Promise接口</title>
</head>
<body>
<script>
/*
const promise = new Promise(function(resolve,reject){
// .... some code
if( flag){ //异步操作成功
resolve(value);
}else{
reject(error);
}
});
//
promise.then(function(value){
//success
},function(error){
//failure
});
*/
// function timeout(ms){
// return new Promise((resolve,reject) => {
// setTimeout(resolve,ms,'done');
// });
// }
// timeout(100).then( (value) => {
// console.log(value);
// });
// let promise = new Promise(function(resolve,reject){
// console.log('Promise');
// resolve();
// });
// promise.then(function(){
// console.log('resolved.');
// });
// console.log('hi!');
//异步加载图片
function loadImageAsync(url){
return new Promise(function(resolve,reject){
const image = new Image();
image.onload = function(){
resolve(image);
}
image.onerror = function(){
reject(new Error('Could not load image at ' + url));
}
image.src = url ;
});
}
//用Promise对象实现Ajax操作
const getJSON = function(url){
const promise = new Promise(function(resolve,reject){
const handler = function(){
if(this.readyState !== 4){
return;
}
if(this.status === 200){
resolve(this.response);
}else{
reject(new Error(this.statusText));
}
};
const client = new XMLHttpRequest();
client.open('GET',url);
client.onreadystatechange = handler;
client.responseType = 'json';
client.setRequestHeader('Accept','application/json');
client.send;
});
return promise;
};
getJSON('/posts.json').then(function(json){
console.log('Contents: ' + json);
},function(error){
console.error('出错了',error);
});
</script>
</body>
</html>