<!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>
<!-- Promise:对象用于表示一个异步操作的最终完成(或失败)及其结果值
好处:
1.逻辑更清晰
2.了解axios函数内部运作机制
3.能解决回调函数地域问题
为什么学习Promise?
成功和失败状态,可以关联对应处理程序,了解axios内部原理
-->
<!-- Promise的三种状态
待定(pending):初始状态,既没有被兑现,也没有被拒绝
已兑现(fulfilled):意味着,操作成功完成
已拒接(rejected):意味着,操作失败
注意:Promise对象一旦被兑现/拒接就是已敲定了,状态无法再被改变
Promise作用:状态改变后调用关联的处理函数
-->
<body>
<script>
/**
* 目标:使用Promise管理异步任务
*/
// 1. 创建Promise对象(pending待定状态)
const p = new Promise((resolve, reject) => {
// 成功调用:resolve(值)触发then()执行
// 失败调用:reject(值)触发catch()执行
// Promise对象创建时,这里的代码都会执行了
// 2. 执行异步代码
setTimeout(() => {
// resolve('模拟AJAX请求-成功结果')
// resolve() => 'fulfilled状态-已兑现' => then()
reject(new Error('模拟AJAX请求-失败结果'))
// reject() => 'rejected状态-已拒绝' => catch()
}, 2000)
})
// 3. 获取结果
p.then(result => {
console.log(result)
// 成功调用
}).catch(error => {
console.log(error)
// 失败调用
})
</script>
</body>
</html>