<!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>Document</title>
</head>
<body>
<script>
// pending 进行中
// fufilled 已成功
// rejected 已失败
let getMarried = (age) => {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (age >= 22) {
resolve("可以结婚了");
} else {
reject("未到结婚年龄");
}
}, 1000);
})
}
const a = getMarried(22);
console.log(a) // 由于setTimeout,时间先后顺序问题:输出pending状态
getMarried(22)
.then((result) => console.log(result)) // 可以结婚了
getMarried(21)
.then((result) => console.log(result))
.catch((err) => console.log(err)) // 未到结婚年龄
let math100 = (grade) => {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (grade >= 90) {
resolve("数学考的不错!");
} else {
reject("数学考的不是很好!")
}
}, 2000)
})
}
let English100 = (grade) => {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (grade >= 90) {
resolve("英语考的不错!");
} else {
reject("英语还需要努力")
}
}, 2000)
})
}
let getToy = () => {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve("奖品已经准备好了")
}, 1000)
})
}
// 依赖关系表达方式1
math100(100)
.then(result => {
console.log(result);
return English100(100)
}) // 数学考的不错!
.then(result => {
console.log(result);
return getToy()
}) // 英语考的不错!
.then(result => console.log(result)) // 奖品已经准备好了
.catch(err => console.log(err))
// 依赖关系表达方式2
/*
关于Promise.all()
Promise.all()接收一个数组为参数,当数组的所有Promise都为resolve状态时,
Promise.all()才会成功,若有一个失败,都会被认为失败
const p = Promise.all([p1, p2, p3])
p的状态有p1,p2,p3决定,分成两种情况。
(1)只有p1,p2,p3的状态都变成fulfilled,p的状态才会变成fulfilled,,
此时p1,p2,p3的返回值组成一个数组,传递给p的回调函数
(2)只要p1,p2,p3之中有一个被rejected,p的状态就会变成rejected,
此时第一个被reject的实例的返回值,会传递给p的回调函数
*/
Promise.all([math100(100), English100(10), getToy()])
.then(result => console.log(result))
.catch(err => console.log(err))
// 英语还需要努力
// 打印所有
// Promise.allSettled 收集所有的执行结果(不论什么状态),以数组形式输出
Promise.allSettled([math100(100), English100(10), getToy()])
.then(result => console.log(result))
.catch(err => console.log(err))
// 0: {
status: "fulfilled", value: "数学考的不错!" }
// 1: {
status: "rejected", reason: "英语还需要努力" }
// 2: {
status: "fulfilled", value: "奖品已经准备好了"}
// 按出现顺序打印
// Promise.race 哪个结果获取的最快,就返回哪个结果,不管结果是成功还是失败
Promise.race([math100(100), English100(10), getToy()])
.then(result => console.log(result)) // 奖品已经准备好了
.catch(err => console.log(err))
let checkFlow = async ()=>{
try{
const res = await math100(100);
console.log(res);
const res2 = await English100(10);
console.log(res2);
const res3 = await getToy();
console.log(res3);
}catch(err){
console.log(err);
}
}
// 数学考的不错!
// 英语还需努力
checkFlow();
</script>
</body>
</html>
promise .then实例化 promise.all .allSettled .race
猜你喜欢
转载自blog.csdn.net/weixin_44158539/article/details/115359249
今日推荐
周排行