当前位置:网站首页>JS提升:如何中断Promise的链式调用
JS提升:如何中断Promise的链式调用
2022-08-01 21:00:00 【The..Fuir】
如何中断Promise的链式调用?
问题:当promise状态改变时,他的链式调用都会生效,那如果我们有这个一个实际需求:我们有5个then(),但其中有条件判断,如当我符合或者不符合第三个then条件时,要直接中断链式调用,不再走下面的then,该如何操作?
我们知道Promise有三种状态:pending(进行中)、fulfilled(已成功)和rejected(已失败),当状态从pending(进行中)变成fulfilled(已成功)或者rejected(已失败)的时候就会调用Promise的then方法, 如果一直在pending(进行中)状态的话,就不会执行到then方法了。
那我们就可以利用这一点去中断Promise的链式调用了,在回调函数中返回一个 pending(进行中) 状态的Promise 对象,这样后面的then方法就不会执行了。
这里的原理是利用了promise.then()返回的新 promise 的结果状态是由 then()指定的回调函数执行的结果决定。也就是说:
如果抛出异常, 新 promise 变为 rejected, reason 为抛出的异常
如果返回的是非 promise 的任意值, 新 promise 变为 resolved, value 为返回的值
如果返回的是另一个新 promise, 此 promise 的结果就会成为新 promise 的结果
所以我们在promise.then()返回了一个pending(进行中) 状态的Promise 对象,promise.then()返回的新 promise 的结果状态就一直是pending(进行中)的,后面的then方法也不会执行了。let p = new Promise((resolve, reject) => {setTimeout(() => { resolve('OK');}, 1000);}); p.then(value => {return new Promise(() => {});}) .then(value => { console.log(222);}) .then(value => { console.log(333);}) .catch(reason => {console.warn(reason);});
永不决议
new Promise(resolve=>{ resolve(1); }).then(value=>{ console.log(value) return 2 }).then(value=>{ console.log(2) return new Promise(()=>{}) }).then(value=>{ console.log(value); return 4; }).then(value=>{ console.log(value); return 5 }).catch(error=>{ console.log(error,'==='); })
原文链接:https://blog.csdn.net/cckevincyh/article/details/124796139
边栏推荐
- 数据库单字段存储多个标签(位移操作)
- Where should I prepare for the PMP exam in September?
- [Energy Conservation Institute] Application of Intelligent Control Device in High Voltage Switchgear
- 案例:MySQL主从复制与读写分离
- 98. Embedded controller EC actual combat EC development board development completed
- Go Atomic
- 织梦通过数据库查询调用当前文章的留言
- vant实现Select效果--单选和多选
- 关于Request复用的那点破事儿。研究明白了,给你汇报一下。
- STAHL触摸屏维修一体机显示屏ET-316-TX-TFT常见故障
猜你喜欢
【Kaggle】House Prices
Excel advanced drawing techniques, 100 (22) - how to respectively the irregular data
StringTable Detailed String Pool Performance Tuning String Concatenation
【Untitled】
技能大赛训练:A部分加固题目
外骨骼机器人(七):标准步态数据库
人工智能可信安全与评测
[Personal Work] Remember - Serial Logging Tool
网络安全与基础设施安全局(CISA):两国将在网络安全方面扩大合作
算法---解码方法(Kotlin)
随机推荐
织梦模板加入php代码
R语言 线性回归的有关方法
外骨骼机器人(七):标准步态数据库
Addition, Subtraction, Multiplication of Large Integers, Multiplication and Division of Large Integers and Ordinary Integers
kubernetes各名词缩写
MySQL Syntax Basics
Where should I prepare for the PMP exam in September?
iptables的使用简单测试
虚拟机的IP地址自动变为127.0.0.1
Batch get protein .pdb files based on Uniprot ID/PDB ID
30+的女性测试人面试经验分享
SkiaSharp 之 WPF 自绘 五环弹动球(案例版)
[Energy Conservation Institute] Ankerui Food and Beverage Fume Monitoring Cloud Platform Helps Fight Air Pollution
Goroutine Leaks - The Forgotten Sender
tiup mirror merge
密码学的基础:X.690和对应的BER CER DER编码
Protocol Buffer 使用
扣减库存方案
Fork/Join线程池
Telnet弱口令渗透测试