-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPromise.html
More file actions
85 lines (81 loc) · 2.38 KB
/
Promise.html
File metadata and controls
85 lines (81 loc) · 2.38 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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<img src="../image/smallimage.jpg" alt="">
<script>
// Promise对象的例子
// function timeout(ms) {
// return new Promise((resolve,reject) => {
// setTimeout(resolve,ms,"DADA");
// })
// }
// timeout(3000).then((value) => {
// console.log(value)
// },(value) =>{
// console.log(1);
// })
// Promise新建以后会立即执行
let promise = new Promise(function (resolve, reject) {
console.log("提交之前");
reject(new Error());
})
promise.then(function () {
console.log("连接数据库成功!")
}).catch((error)=>{
console.log(error)
})
console.log("hi");
// Promise.reslove()方法将现有对象转换为Promise对象
var p = Promise.resolve("foo");
console.log(p);
p.then(x=>console.log(x));
// (2)参数是thenable对象
var thenable = {
then:function (resolve,reject) {
resolve(42)
}
};
// Promise.reject()方法会返回一个新的Promise实例,状态为rejected
var p1 = Promise.reject("出错啦");
p1.then(function () {
console.log("已完成!")
}).catch((error) =>console.log(error));
/** 自己部署一个done方法:我们可以提供一个done方法,总是处于回调链的尾端,保证抛
出任何可能出现的错误**/
Promise.prototype.done = function (onFulfiled,onRejected) {
this.then(onFulfiled,onRejected)
.catch(function (reason) {
setTimeout(()=>{throw reason},0);
})
}
var P = Promise.resolve(thenable);
P.then(function (value) {
console.log(value);
})
P.then(function (reslove,reject,value) {
console.log(value)
throw new Error;
}).done(function () {
});
// 应用
// (1)图片的加载
const preloadImage = function (path) {
return new Promise(function (resolve,reject) {
var image = new Image();
image.onload = resolve;
image.onerror =reject;
image.src = path
})
}
preloadImage("../image/bigimage00.jpg").then(function () {
alert(1)
}).catch(function () {
alert("出错啦")
});
</script>
</body>
</html>