JS中Promise用法(简要说明)

1、下方自定义名词约定

  • IIFE:立即执行函数
  • positive: 正向结果接收函数(resolve),异步回调后用这个函数接收数据并改变promise状态
  • data: 正向数据
  • negative: 负向结果接收函数(reject),异步回调后用这个函数接收原因并改变promise状态
  • reason: 负向原因

2、官方流程图

在这里插入图片描述

3、构造函数Promise + <状态>fulfilled 用法

代码

//抽象伪代码例子
new Promise( IIFE(positive, negative){ positive(data) } )
//具体例子
let testP = new Promise(function(positive, negative){
    setTimeout(()=>{
        positive("success.");
        console.log(`延迟执行完毕,用positive设置正向结果,并改变promise的状态`);
    }, 5000);
});

图示

在这里插入图片描述

4、构造函数Promise + <状态>rejected 用法

代码

//抽象伪代码例子
new Promise( IIFE(positive, negative){ negative(reason) } )
//具体例子
let testFail = new Promise(function(positive, negative){
    setTimeout(()=>{
        negative("failure.");
        console.log(`延迟执行完毕,异步回调后用negative这个函数接收原因并改变promise状态`);
    }, 5000);
});

图示

在这里插入图片描述

5、第3和4结合使用,可以将promise状态settled为2种情况之一

代码

// 下方的 xxx 每次执行都要用一个新变量接收新的结果
let xxx = new Promise(function(positive, negative){
    setTimeout(()=>{
        let rst = Math.floor(Math.random()*100);
        if(rst%2==0){
            positive(`偶数=>${rst}`);
        }else{
            negative(`奇数=>${rst}`); //注意,下方图示调用错误,总是fulfilled态;以运行这个最新代码为准
        }
    }, 5000);
});

图示(图中if和else都是调用positive不太对,以代码为准)

在这里插入图片描述
在这里插入图片描述

6、then的用法

代码

new Promise(function(positive, negative){
    // setTimeout(()=>{
        let rst = Math.floor(Math.random()*100);
        if(rst%2==0){
            positive(`偶数=>${rst}`);
        }else{
            negative(`奇数=>${rst}`);
        }
    // }, 0);
})
.then(
(data)=>{
    console.log(`then的第一个参数函数,接收正向结果=>${data}`);
},
(reason)=>{
    console.log(`then的第二个参数函数,接收负向原因=>${reason}`);
});

图示

触发对应的处理函数

在这里插入图片描述

7、catch的用法

概括

  1. catch等价于then的第2个处理函数,当then没有第2个处理函数时
  2. catch还等价于try catch,当then第1个处理函数运行出错时

代码

//catch是和promise对象的then函数并行的函数
//catch顾名思义,类似try{}catch(e){},用来捕获异常的(promise的catch能捕获2种情况《1、没有then的第2个函数参数时|||2、then的第1个函数参数运行出错时)》如下)

//1、当then函数没有第二个参数(用来处理negative原因的函数),catch能够捕获到并处理【等价于then的第2个函数参数,在then没有第2个参数时】
new Promise((positive, negative)=>{
    negative("负向原因。")
})
.then(
    (data)=>{ console.log("上面是negative,不会进到这里" + data) }
    // (reason)=>{ console.log("上面是negative,会进来" + reason + "但是我注释掉了,所以这里没处理到。") }
)
.catch( //控制台输出:   捕获negative原因,并输出:undefined ___ 负向原因。
    (reason, data)=>{ console.log(`捕获negative原因,并输出:${data} ___ ${reason}`) }
);

//1-1、这里拓展下,如果then有第二个参数,即接收negative原因并处理的函数,正常catch是执行不了的【then有第2个参数,catch无效】
new Promise((positive, negative)=>{
    negative("负向原因。")
})
.then(
    (data)=>{ console.log("上面是negative,不会进到这里" + data) },
    (reason)=>{ console.log("上面是negative,会进来" + reason + "但是我注释掉了,所以这里没处理到。") }
)
.catch(
    (reason, data)=>{ console.log(`捕获negative原因,并输出:${data} ___ ${reason}`) }
);

2、then的第一个函数参数运行出错,能catch到报错使js程序不至于暂停(这就是相当于try catch的能力了)
new Promise((positive, negative)=>{
    positive("正向数据,进入then的第1个处理函数——————")
    // negative("负向原因。")
})
.then(
    (data)=>{ 
    	console.log(data); //控制台输出:正向数据,进入then的第1个处理函数——————
   		console.log(`特意使用不存在的变量${notExistVariable_willError}`); 
   	},
    (reason)=>{ console.log(reason); }
)
.catch(//控制台输出:then的第1个函数使用了不存在的变量,报错:ReferenceError: notExistVariable_willError is not defined ___ undefined
    (reason, data)=>{ console.log(`then的第1个函数使用了不存在的变量,报错:${reason} ___ 接收到的数据:${data}`) }
);


8、all的用法

概括

  • all函数的数组参数中的所有的promise都成功执行完毕时触发then的第一个函数参数,只要任意没有成功都触发then的第2个函数参数。

代码

Promise.all([
    new Promise((positive, negative)=>{
       positive("成功1"); 
    }),
    new Promise((positive, negative)=>{
       positive("成功2"); 
    }),
    new Promise((positive, negative)=>{
       positive("成功3"); 
    }),
])
.then(
    (results)=>{ console.log(`成功结果集:${results.join(",")}`) },
    (reason)=>{ console.log(`毕成功,所以不可能有reason=> ${reason}`); }
);
//控制台输出: 成功结果集:成功1,成功2,成功3

9、race() //竞态

概括

  • race数组参数中的promise都是竞争关系,任意完成(不管是调用positive还是negative),都会执行then,并且后续race数组参数中的剩余promise如果完成了也不再触发then了。

代码

//以下代码总是输出: 成功偶数111=>xx  或者 失败奇数111=>xx , 即:
//					只会在执行race数组参数中的第一个promise后,触发与race同级的then一次。
Promise.race([
    new Promise((positive, negative)=>{
       let numIn_100 = Math.floor(Math.random()*100);
       if(numIn_100%2==0){
           positive(`成功偶数111=>${numIn_100}`);
       }else{
           negative(`失败奇数111=>${numIn_100}`);
       }
    }),
    new Promise((positive, negative)=>{
       positive("失败2222"); 
    }),
    new Promise((positive, negative)=>{
       negative("成功3333"); 
    }),
])
.then(
    (data)=>{ console.log(`positive data:${data}`) },
    (reason)=>{ console.log(`negative reason=> ${reason}`); }
);
  • 15
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值