/
03promise基本使用.html
37 lines (36 loc) · 1.51 KB
/
03promise基本使用.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
<!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>promise基本使用</title>
</head>
<body>
<script>
// 1. 创建一个新的promise对象
const p = new Promise((resolve, reject) => { // 执行器函数 同步回调
console.log('-------------执行 excutor 执行器函数---------------1') // 先执行
// 2. 执行异步操作任务
setTimeout(() => {
console.log('-------------异步任务中的回调函数 --------------3')
const time = Date.now() // 如果当前时间是偶数就代表成功,否则就代表失败
if (time%2 == 0){// 3.1 如果成功了,调用resolve(value)
resolve('成功的数据 time=' + time) // value = '成功的数据 time=' + time
}else{// 3.2 如果失败了,调用reject(reason)
reject('失败的数据 time=' + time) // reason = '失败的数据 time=' + time
}
}, 1000);
});
console.log('-------------new Promise() 之后--------------2')
p.then(
value => { // 接收得到成功的value数据 onResolved
console.log('成功的回调', value) // 成功的回调 成功的数据 time=1612949194514
},
reason => { // 接收得到失败的reason数据 onRejected
console.log('失败的回调', reason) // 失败的回调 失败的数据 time=1612949218973
}
)
</script>
</body>
</html>