<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>promise</title>
</head>
<body>
</body>
<script>
function asyncFun1() {
return new Promise(function (resolve, reject) {
setTimeout(() => {
var num = Math.floor(Math.random() * 900 + 100);
console.log("fun1num:",num)
if (num > 500) {
resolve({
code: '1',
num: num,
from:'fun1'
})
} else {
reject({
code: 'error',
num: -1,
from:'fun1'
})
}
}, 1500)
})
}
function asyncFun2(num1) {
return new Promise(function (resolve, reject) {
setTimeout(() => {
var num = Math.floor(Math.random() * 900 + 100);
console.log("fun2num:",num)
if (num > 500) {
let total = num1 + num;
console.log(num1)
resolve({
total:total
})
} else {
reject({
code: 'error',
num: -1,
from:'fun2'
})
}
}, 1000)
})
}
// 1. 串行
// asyncFun1().then(res=>{
// console.log("第一个方法",res)
// return res.num
// }).then(parmeFor1=>{
// console.log("第一个then的返回值",parmeFor1)
// return asyncFun2(parmeFor1)
// }).then(res3=>{
// console.log("第三个then执行",res3)
// }).catch(err=>{
// console.log("失败了",err)
// })
//2.并行 返回的是promise对象,返回状态有一个失败且都失败,
// let p1 = asyncFun1();
// let p2 = asyncFun2();
// Promise.all([p1,p2]).then(res=>{
// console.log(res)
// }).catch(err=>{
// console.log("err",err)
// })
//3. any 任何一个先resolve就resolve,全部是否就reject
// Promise.any([asyncFun1(),asyncFun2()]).then(res=>{
// console.log("any",res)
// }).catch(err=>{
// console.log("err",err)
// })
//4. race 看谁跑得快,就返回哪一个
// Promise.race([asyncFun1(),asyncFun2()]).then(res=>{
// console.log("race",res)
// }).catch(err=>{
// console.log("err",err)
// })
//5. allSettled 每一个异步任务都想得到结果就使用Promise.allSettled()
Promise.allSettled([asyncFun1(),asyncFun2()]).then(res=>{
console.log("allSettled",res)
}).catch(err=>{
console.log("err",err)
})
</script>
</html>
promise 4个方法
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...