当前位置:网站首页>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
边栏推荐
- 任务调度线程池-应用定时任务
- 职场如象棋,测试/开发程序员如何突破成长瓶颈期?
- 【Kaggle】House Prices
- LinkedList source code sharing
- 列表页常见的 hook 封装
- Nacos 配置中心
- [Energy Conservation Institute] Application of Intelligent Control Device in High Voltage Switchgear
- MySQL Syntax Basics
- 和我一起写一个音乐播放器,听一首最伟大的作品
- 漏洞分析丨HEVD-0x6.UninitializedStackVariable[win7x86]
猜你喜欢
随机推荐
Simple test of the use of iptables
Hiking, cured my mental internal friction
网络安全与基础设施安全局(CISA):两国将在网络安全方面扩大合作
Protocol Buffer 使用
Interpretation of the meaning of each dimension of two-dimensional, three-dimensional, and four-dimensional matrices
Zheng Xiangling, Chairman of Tide Pharmaceuticals, won the "2022 Outstanding Influential Entrepreneur Award" Tide Pharmaceuticals won the "Corporate Social Responsibility Model Award"
使用百度EasyDL实现厂区工人抽烟行为识别
StringTable详解 串池 性能调优 字符串拼接
tiup mirror clone
360借条安全专家:陌生微信好友不要轻易加贷款推广多是诈骗
线上问题排查常用命令,总结太全了,建议收藏!!
扣减库存方案
tiup mirror merge
2022年秋招,软件测试开发最全面试攻略,吃透16个技术栈
Application of Acrel-5010 online monitoring system for key energy consumption unit energy consumption in Hunan Sanli Group
【Untitled】
Where should I prepare for the PMP exam in September?
tiup mirror genkey
PyTorch笔记 - Attention Is All You Need (2)
Failed to re-init queues : Illegal queue capacity setting (abs-capacity=0.6) > (abs-maximum-capacity





![[Personal Work] Remember - Serial Logging Tool](/img/8c/56639e234ec3472f4133342eec96d6.png)



