当前位置:网站首页>JS hoisting: how to break the chain of Promise calls
JS hoisting: how to break the chain of Promise calls
2022-08-01 21:03:00 【The..Fuir】
How to break the chain of Promise calls?
Problem: When the state of promise changes, his chained calls will take effect, then if we have this actual requirement: we have 5 then(), but there are conditional judgments, such as when I meet or not meet the firstWhen there are three then conditions, how to directly interrupt the chain call and no longer go to the following then?
We know that Promise has three states: pending (in progress), fulfilled (successful) and rejected (failed), when the state changes from pending (in progress)) becomes fulfilled (successful) or rejected (failed), the then method of Promise will be called. If it has been in the pending (in progress) state, the then method will not be executed.
Then we can use this to interrupt the chained call of Promise, and return a Promise object in the pending (in progress) state in the callback function, so that the then method will notimplemented.
The principle here is that the result state of the new promise returned by promise.then() is determined by the result of the callback function specified by then().That is:
If an exception is thrown, the new promise becomes rejected, and the reason is the thrown exception
If any value other than a promise is returned, the new promise becomes resolved, and value is the returned value
IfWhat is returned is another new promise, and the result of this promise will become the result of the new promise
So we return a promise object in the pending (in progress) state in promise.then(), The result status of the new promise returned by promise.then() is always pending (in progress), and the then method will not be executed.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);});
Never decide
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,'===');})
Original link: https://blog.csdn.net/cckevincyh/article/details/124796139
边栏推荐
猜你喜欢
随机推荐
Questions I don't know in database kernel interview(1)
Protocol Buffer 使用
写给刚进互联网圈子的人,不管你是开发,测试,产品,运维都适用
响应式织梦模板美容整形类网站
2022年秋招,软件测试开发最全面试攻略,吃透16个技术栈
案例:MySQL主从复制与读写分离
[译] 容器和 Kubernetes 中的退出码完整指南
4.1 配置Mysql与注册登录模块
漏洞分析丨HEVD-0x6.UninitializedStackVariable[win7x86]
C语言之字符串函数二
30+的女性测试人面试经验分享
Pytorch框架学习记录8——最大池化的使用
pytest:开始使用
LeetCode每日一题(1807. Evaluate the Bracket Pairs of a String)
iptables的使用简单测试
列表页常见的 hook 封装
织梦模板加入php代码
Pytorch框架学习记录9——非线性激活
Godaddy domain name resolution is slow and how to use DNSPod resolution to solve it
面试突击70:什么是粘包和半包?怎么解决?