资料
链接:https://pan.baidu.com/s/1pQpaX4OJtRZILJf87pBQpg?pwd=9f8n
提取码:9f8n
课程的五大部分内容:
1.介绍与基本使用
2.Promise的API
3.Promise 中的几个关键问题
4.自定义封装
5.async和await(异步编程的终极解决方案)
回调函数的方式:
fs 文件操作
require('fs').readFile('./index.html', (err,data)=>{
})
数据库操作
AJAX
$.get('/server', (data)=>{
})
定时器
setTimeout(()=>{
}, 2000);
实例对象中的一个属性 『PromiseState』
实例对象中的另一个属性 『PromiseResult』
保存着异步任务『成功/失败』的结果
抽象表达
Promise 的状态改变
promise 的状态
状态改变
pending 变为 resolved | fulfilled
pending 变为 rejected
说明: 只有这 2 种, 且一个 promise 对象只能改变一次
无论变为成功还是失败, 都会有一个结果数据
成功的结果数据一般称为 value, 失败的结果数据一般称为 reason

<script>
// 1) 创建 promise 对象(pending 状态), 指定执行器函数
const p = new Promise((resolve, reject) => {
// 2) 在执行器函数中启动异步任务
setTimeout(() => {
const time = Date.now()
// 3) 根据结果做不同处理
// 3.1) 如果成功了, 调用 resolve(), 指定成功的 value, 变为 resolved 状 态
if (time % 2 === 1) {
resolve('成功的值 ' + time)
} else {
// 3.2) 如果失败了, 调用 reject(), 指定失败的 reason, 变为
rejected
状态
reject('失败的值' + time)
}
}, 2000)
})
// 4) 能 promise 指定成功或失败的回调函数来获取成功的 vlaue 或失败的 reason
p.then(
value => {
// 成功的回调函数 onResolved, 得到成功的 vlaue
console.log('成功的 value: ', value)
},
reason => {
// 失败的回调函数 onRejected, 得到失败的 reason
console.log('失败的 reason: ', reason)
})
</script>
![[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-HkpQZZE0-1661042247432)(G:\Project\Typora\Image\回调地狱.jpg)]](https://1000bd.com/contentImg/2024/03/29/f1522f776f44671a.jpeg)
什么是回调地狱?
回调函数嵌套调用, 外部回调函数异步执行的结果是嵌套的回调执行的条件
回调地狱的缺点?
不便于阅读
不便于异常处理
解决方案?
Promise链式调用
终极解决方案?
async/await
doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>基本使用title>
<link crossorigin='anonymous' href="https://cdn.bootcss.com/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
head>
<body>
<div class="container">
<h2 class="page-header">Promise 初体验h2>
<button class="btn btn-primary" id="btn">点击抽奖button>
div>
<script>
//生成随机数
function rand(m,n){
return Math.ceil(Math.random() * (n-m+1)) + m-1;
}
/**
点击按钮, 1s 后显示是否中奖(30%概率中奖)
若中奖弹出 恭喜恭喜, 奖品为 10万 RMB 劳斯莱斯优惠券
若未中奖弹出 再接再厉
*/
//获取元素对象
const btn = document.querySelector('#btn');
//绑定单击事件
btn.addEventListener('click', function(){
//定时器
// setTimeout(() => {
// //30% 1-100 1 2 30
// //获取从1 - 100的一个随机数
// let n = rand(1, 100);
// //判断
// if(n <= 30){
// alert('恭喜恭喜, 奖品为 10万 RMB 劳斯莱斯优惠券');
// }else{
// alert('再接再厉');
// }
// }, 1000);
//Promise 形式实现
// resolve 解决 函数类型的数据
// reject 拒绝 函数类型的数据
const p = new Promise((resolve, reject) => {
setTimeout(() => {
//30% 1-100 1 2 30
//获取从1 - 100的一个随机数
let n = rand(1, 100);
//判断
if(n <= 30){
resolve(n); // 将 promise 对象的状态设置为 『成功』
}else{
reject(n); // 将 promise 对象的状态设置为 『失败』
}
}, 1000);
});
console.log(p);
//调用 then 方法
// value 值
// reason 理由
p.then((value) => {
alert('恭喜恭喜, 奖品为 10万 RMB 劳斯莱斯优惠券, 您的中奖数字为 ' + value);
}, (reason) => {
alert('再接再厉, 您的号码为 ' + reason);
});
});
script>
body>
html>
<script>
// 1) 创建 promise 对象(pending 状态), 指定执行器函数
const p = new Promise((resolve, reject) => {
// 2) 在执行器函数中启动异步任务
setTimeout(() => {
const time = Date.now()
// 3) 根据结果做不同处理
// 3.1) 如果成功了, 调用 resolve(), 指定成功的 value, 变为 resolved 状 态
if (time % 2 === 1) {
resolve('成功的值 ' + time)
} else {
// 3.2) 如果失败了, 调用 reject(), 指定失败的 reason, 变为rejected状态
reject('失败的值' + time)
}
}, 2000)
})
// 4) 能 promise 指定成功或失败的回调函数来获取成功的 vlaue 或失败的 reason
p.then(
value => {
// 成功的回调函数 onResolved, 得到成功的 vlaue
console.log('成功的 value: ', value)
},
reason => {
// 失败的回调函数 onRejected, 得到失败的 reason
console.log('失败的 reason: ', reason)
})
script>
doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>基本使用title>
head>
<body>
<script>
function doDelay(time) {
// 1. 创建 promise 对象
return new Promise((resolve, reject) => {
// 2. 启动异步任务
console.log('启动异步任务')
setTimeout(() => {
console.log('延迟任务开始执行...')
// 假设: 时间为奇数代表成功, 为偶数代表失败
const time = Date.now()
// 成功了
if (time % 2 === 1) {
// 3. 1. 如果成功了, 调用 resolve()并传入成功的 value
resolve('成功的数据 ' + time)
} else {
// 失败了
// 3.2. 如果失败了, 调用 reject()并传入失败的 reason
reject('失败的数据 ' + time)
}
}, time)
})
}
const promise = doDelay(2000)
promise.then(
value => {
console.log('成功的 value: ', value)
},
reason => {
console.log('失败的 reason: ', reason)
},
)
script>
body>
doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>基本使用title>
head>
<body>
<script>
/*
可复用的发 ajax 请求的函数: xhr + promise
*/
function promiseAjax(url) {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest()
xhr.onreadystatechange = () => {
if (xhr.readyState !== 4) return
const {
status, response} = xhr
// 请求成功, 调用 resolve(value)
if (status >= 200 && status < 300) {
resolve(JSON.parse(response))
} else {
// 请求失败, 调用 reject(reason)
reject(new Error('请求失败: status: ' + status))
}
}
xhr.open("GET", url)
xhr.send()
})
}
promiseAjax('https://api.apiopen.top2/getJoke?page=1&count=2&type=video').then(
data => {
console.log('显示成功数据', data)
}, error => {
alert(error.message)
}
)
script>
body>
doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>基本使用title>
head>
<body>
<script>
// 成功的回调函数
function successCallback(result) {
console.log("声音文件创建成功: " + result);
}
// 失败的回调函数
function failureCallback(error) {
console.log("声音文件创建失败: " + error);
}
/* 1.1 使用纯回调函数 */
createAudioFileAsync(audioSettings, successCallback, failureCallback)
/* 1.2. 使用 Promise */
const promise = createAudioFileAsync(audioSettings); // 2
setTimeout(() => {
promise.then(successCallback, failureCallback);
}, 3000);
/*
2.1. 回调地狱
*/
doSomething(function (result) {
doSomethingElse(result, function (newResult) {
doThirdThing(newResult, function (finalResult) {
console.log('Got the final result: ' + finalResult)
}, failureCallback)
}, failureCallback)
}, failureCallback)
/*
2.2. 使用 promise 的链式调用解决回调地狱
*/
doSomething().then(function (result) {
return doSomethingElse(result)
}).then(function (newResult) {
return doThirdThing(newResult)
}).then(function (finalResult) {
console.log('Got the final result: ' + finalResult)
}).catch(failureCallback)
/*
2.3. async/await: 回调地狱的终极解决方案
*/
async function request() {
try {
const result = await doSomething()
const newResult = await doSomethingElse(result)
const finalResult = await doThirdThing(newResult)
console.log('Got the final result: ' + finalResult)
} catch (error) {
failureCallback(error)
}
}
script>
body>
//
const fs = require('fs');
//回调函数 形式
// fs.readFile('./resource/content.txt', (err, data) => {
// // 如果出错 则抛出错误
// if(err) throw err;
// //输出文件内容
// console.log(data.toString());
// });
//Promise 形式
let p = new Promise((resolve , reject) => {
fs.readFile('./resource/content.txt', (err, data) => {
//如果出错
if(err) reject(err);
//如果成功
resolve(data);
});
});
//调用 then
p.then(value=>{
console.log(value.toString());
}, reason=>{