js异步编程promise 和 async+await
发表于:2026-06-19 11:00:03浏览:0次
一:为什么需要异步编程
目前有一个需求,需要你按照以下的逻辑去进行接口请求:
1 先去请求接口 A
2 在接口 A 获取到数据之后,再去请求接口 B
3 在接口 B 获取到数据之后,再去请求接口 C
4 在接口 C 获取到数据之后,再去请求接口 D
A(function (res) {
console.log(res);
B(function (res) {
console.log(res);
C(function (res) {
console.log(res);
D(function (res) {
console.log(res);
})
})
})
})
会出现一个问题:回调地狱 -> 回调函数的大量嵌套导致出现 复杂且难以阅读 的逻辑。
二:promise
1:promise是什么
使用 Promise 进行定义接口:Promise 对象用于表示一个异步操作的最终完成 (或失败)及其结果值。它一个构造函数,所以可以通过 new 关键字来构建它,获取实例。
2:promise三种状态
- 待定(pending): 初始状态,既没有被兑现,也没有被拒绝。
- 已兑现(fulfilled): 意味着操作成功完成。
- 已拒绝(rejected): 意味着操作失败。
3:promise三个方式进行链式调用解决回调地狱
- 成功:promise.then()
- 失败:promise.catch()
- 结束:promise.finally()
const isA = true
const isB = true
const isC = true
const isD = true
function A() {
// 1. 创建 Promise 实例
return new Promise((resolve, reject) => {
// 2. 当前处于 【待定(pending)】 状态下
console.log('执行 A 接口的逻辑')
setTimeout(() => {
if (isA) {
// 3. 进入 【已兑现(fulfilled)】 状态下
resolve('接口 A 执行完成')
} else {
// 4. 进入 【已拒绝(rejected)】 状态下
reject('接口 A 执行失败')
}
}, 1000)
})
}
function B() {
return new Promise((resolve, reject) => {
console.log('执行 B 接口的逻辑')
setTimeout(() => {
if (isB) {
resolve('接口 B 执行完成')
} else {
reject('接口 B 执行失败')
}
}, 1000)
})
}
function C() {
return new Promise((resolve, reject) => {
console.log('执行 C 接口的逻辑')
setTimeout(() => {
if (isC) {
resolve('接口 C 执行完成')
} else {
reject('接口 C 执行失败')
}
}, 1000)
})
}
function D() {
return new Promise((resolve, reject) => {
console.log('执行 D 接口的逻辑')
setTimeout(() => {
if (isD) {
resolve('接口 D 执行完成')
} else {
reject('接口 D 执行失败')
}
}, 1000)
})
}
// 获取 Promise 实例
A()
// 通过 .then 方法获取当前 Promise 的执行结果
.then(res => {
console.log(res);
// 标记下一步进入 B 方法
return B()
})
// 继续 .then 进行下一次的异步操作
.then(res => {
console.log(res);
// 标记下一步进入 C 方法
return C()
})
// 继续 .then 进行下一次的异步操作
.then(res => {
console.log(res);
// 标记下一步进入 D 方法
return D()
})
// 继续 .then 进行下一次的异步操作
.then(res => {
console.log(res);
// 结束
})
三:async+await
使用 async 和 awiat 可以简化 Promise 的异步操作,把 Promise 的异步操作变为同步写法
async:标记一个函数为异步函数
await:标记当前操作为异步操作,await 关键字只能使用在被 【async标记的函数中】
async function test() {
const resA = await A();
console.log(resA);
const resB = await B();
console.log(resB);
const resC = await C();
console.log(resC);
const resD = await D();
console.log(resD);
}
