说明
https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Promise
Promise 对象表示异步操作最终的完成(或失败)以及其结果值。
用Promise 的好处:
- 逻辑更清晰
- 能解决回调函数地狱问题
// 1. 创建Promise对象
const p = new Promise((resolve, reject) => {
// 2. 执行异步任务,并传递结果
// 成功以后调用:resolve(值) 触发then() 执行
// 失败以后调用:reject(值) 触发catch()执行
})
// 3. 接收结果
p.then(result => {
// 成功
}).catch(error => {
// 失败
})
示例
模拟异步请求成功执行的结果
<!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>
/**
* 目标:使用Promise管理异步任务
*/
// 1. 创建Promise对象
const p = new Promise((resolve, reject) => {
// 2. 执行异步代码
setTimeout(() => {
resolve('模拟异步请求成功的结果')
}, 5000)
})
// 3. 获取结果
p.then(result => {
console.log(result)
})
</script>
</body>
</html>
模拟异步请求执行失败的结果
<!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>
/**
* 目标:使用Promise管理异步任务
*/
// 1. 创建Promise对象
const p = new Promise((resolve, reject) => {
// 2. 执行异步代码
setTimeout(() => {
// resolve('模拟异步请求成功的结果')
reject(new Error('模拟异步请求失败的结果'))
}, 5000)
})
// 3. 获取结果
p.then(result => {
console.log(result)
}).catch(error => {
console.log(error)
})
</script>
</body>
</html>