24. Promise是什么?怎么用?
1. Promise定义
Promise
是一种异步编程的解决方案。它可以使异步操作更加清晰、简单、优雅,避免了回调地狱
的问题。Promise
对象表示一个异步操作的最终完成或失败,并且它的最终状态(完成或失败)和返回值(或错误)不依赖于调用它的代码。
2. Promise状态
Promise
对象有三个状态:pending
(等待中)、fulfilled
(已完成)和 rejected
(已拒绝)。Promise
实例是在创建时就立即执行的,并返回一个 Promise 对象。通过使用 then
方法可以注册成功(fulfilled
)和失败(rejected
)状态的回调函数。
3. Promise基本用法:
// 异步获取数据
function getData(name) {
return new Promise((resolve, reject) => {
setTimeout(() => {
if(name === "Jack") {
resolve({
name: "Jack", age: 20})
} else {
reject("请求错误!")
}
}, 2000)
})
}
getData("Jack").then(res => {
console.log(res);//{name: 'Jack', age: 20}
}).catch(err => {
console.log(err);
});
getData("Jarry").then(res => {
console.log(res);
}).catch(err => {
console.log(err);//请求错误!
});
4. Promise的实例方法和类方法
1. 实例方法: then()、catch()和finally(),Promise的实例方法返回的都是Promise对象,都可以链式调用
- then()方法
// then() fulfilled和rejected状态都不可修改,即先执行的先生效
const p1 = new Promise((resolve, reject) => {
resolve("then res");//fulfilled状态
reject("then err");//rejected状态
})
p1.then(res => {
console.log(res);//then res
}, err => {
console.log(err);
})
const p2 = new Promise((resolve, reject) => {
reject("then err");//rejected状态
resolve("then res");//fulfilled状态
})
p2.then(res => {
console.log(res);
}, err => {
console.log(err);//then err
})
// then()方法的链式调用 then方法使用上个then方法的返回值作为参数
const p3 = new Promise((resolve, reject) => {
resolve("then res1")
})
p3.then(res => {
console.log(res);//then res1
return "then res2"
}).then(res => {
console.log(res);//then res2
return "then res3"
}).then(res => {
console.log(res);//then res3
})
- catch()方法
// catch方法是then(null, err => {})的语法糖
const p4 = new Promise((resolve, reject) => {
reject("catch err")
})
p4.then(null, err => {
console.log(err);//catch err
})
p4.catch(err => {
console.log(err);//catch err
})
// catch()方法链式调用
p4.catch(err => {
console.log(err);//catch err
throw "catch err1"
}).catch(err => {
console.log(err);//catch err1
throw "catch err2"
}).catch(err => {
console.log(err);//catch err2
})
- finally()方法
// finally()方法 不管什么状态最终都会执行
const p5 = new Promise((resolve, reject) => {
resolve("fulfilled")
// reject("rejected")
})
p5.then(res => {
console.log(res);//fulfilled
}).catch(err => {
console.log(err);//
}).finally(() => {
console.log("finally msg");//finally msg
})
// finally()链式调用 finally的回调函数没有参数
p5.then(res => {
console.log(res);//fulfilled
}).finally(() => {
console.log("finally msg1");//finally msg1
return "finally res"
}).finally((res) => {
console.log(res);//undefined
console.log("finally msg2");//finally msg2
})
2. 类方法(静态方法): resolve()、reject()、all()、allSettled()、race()和any(),可以用来创建 Promise 对象、处理多个 Promise 对象、转换非 Promise 对象为 Promise 对象等等
- resolve()
// resolve()
// 1. 传入普通值
const p6 = Promise.resolve("resolve res")
// 相当于
const p7 = new Promise((resolve, reject) => {
resolve("resolve res")
})
p6.then(res => console.log(res));//resolve res
p7.then(res => console.log(res));//resolve res
// 2. 传入Promise 直接返回这个Promise对象
const p8 = Promise.resolve(p7)
p8.then(res => console.log(res));//resolve res
// 3. 传入thenable对象 包装成Promise后返回
const p9 = Promise.resolve({
then: (resolve, reject) => {
resolve("thenable resolve res")
}})
p9.then(res => console.log(res));//thenable resolve res
- reject()
// reject() Promise.reject(reason):创建一个状态为已拒绝(rejected)并且拒绝原因为 reason 的 Promise 对象。
// 1. 传入普通值
const p10 = Promise.reject("reject msg")
p10.catch(err => console.log(err));//reject msg
// 2. 传入Promise Promise包一层rejected状态的Promise返回
const p11 = Promise.reject(new Promise((resolve, reject) => {
resolve("Promise reject msg")
}))
p11.catch(err => {
err.then(res => {
console.log(res);//Promise reject msg
})
})
// 3. 传入thenable 返回的thenable对象当做错误信息输出
const p12 = Promise.reject({
then: (resolve, reject) => {
reject("thenable reject msg")
}})
p12.catch(err => console.log(err));//{then: ƒ}
- all()
Promise.all(iterable)
:接收一个可迭代对象(如数组),返回一个新的Promise
对象。如果可迭代对象中的所有Promise
对象都变成已解决状态,则返回的Promise
对象变成已解决状态,并且其值为一个数组,数组中的元素分别是可迭代对象中每个Promise
对象的解决结果;否则,返回的Promise
对象变成已拒绝状态,并且其拒绝原因为第一个拒绝的Promise
对象的拒绝原因。
//全部resolve,等最后一个状态变成fulfilled时,输出结果
const promise1 = new Promise((resolve, reject) => {
setTimeout(() => {
resolve("Promise1");
}, 1000)
})
const promise2 = new Promise((resolve, reject) => {
setTimeout(() => {
resolve("Promise2");
}, 2000)
})
const promise3 = new Promise((resolve, reject) => {
setTimeout(() => {
resolve("Promise3");
}, 3000)
})
Promise.all([promise1, promise2, promise3]).then(res => {
console.log(res);//['Promise1', 'Promise2', 'Promise3']
}).catch(err => {
console.log(err);
})
//遇到第一个reject就中止并抛出错误
const promise1 = new Promise((resolve, reject) => {
setTimeout(() => {
resolve("Promise1");
}, 1000)
})
const promise2 = new Promise((resolve, reject) => {
setTimeout(() => {
// resolve("Promise2");
reject("Promise2 reject");
}, 2000)
})
const promise3 = new Promise((resolve, reject) => {
setTimeout(() => {
// resolve("Promise3");
reject("Promise3 reject");
}, 3000)
})
Promise.all([promise1, promise2, promise3]).then(res => {
console.log(res);//['Promise1', 'Promise2', 'Promise3']
}).catch(err => {
console.log(err);//Promise2 reject
})
- allSettled()
// allSettled() 把所有的对应的状态和值输出
Promise.allSettled([promise1, promise2, promise3]).then(res => {
console.log(res);//[{status: 'fulfilled', value: 'Promise1'}, {status: 'rejected', reason: 'Promise2 reject'}, {status: 'rejected', reason: 'Promise3 reject'}]
}).catch(err => {
console.log(err);
})
- race()
//比赛,谁先改变状态就返回谁的值
Promise.race([promise1, promise2, promise3]).then(res => {
console.log(res);//Promise1
}).catch(err => {
console.log(err);
})
- any()
// any() 有一个状态变为fulfilled则改变状态并返回第一个fulfilled状态的值,若全部状态都为rejected,则返回rejected状态
Promise.any([ promise2, promise3]).then(res => {
console.log(res);
}).catch(err => {
console.log(err);//AggregateError: All promises were rejected
})