当前位置:网站首页>Promise to learn several key questions (3) the Promise - state change, execution sequence and mechanism, multitasking series, abnormal penetration, interrupt the chain of Promise
Promise to learn several key questions (3) the Promise - state change, execution sequence and mechanism, multitasking series, abnormal penetration, interrupt the chain of Promise
2022-08-01 10:34:00 【I'm sorry the user has become immortal】
目录
前言
问题一、Promise 状态的改变?
1. resolve transition to successful state
resolve(value)
: 如果当前是pending
就会变为fulfilled (resolved)
let p = new Promise((resolve, reject) => {
resolve('ok'); // pending => fulfilled (resolved)
});
console.log(p);
p.then(value => {
console.log(value);
}, reason => {
console.log(reason);
})
2. reject transition to successful state
reject(reason)
: 如果当前状态是pending
就会变为rejected
let p = new Promise((resolve, reject) => {
reject("err"); // pending => rejected
});
console.log(p);
p.catch(reason => {
console.log(reason);
})
3. Throws an exception to fail
抛出异常
: 如果当前是pending
就会变为rejected
let p = new Promise((resolve, reject) => {
throw '出错了';
});
console.log(p);
p.catch(reason => {
console.log(reason);
})
注:For the above failure state can be executed
catch 方法
to handle failed callbacks
问题二、一个 promise 指定多个成功/失败回调函数, 都会调用吗?
当 promise 改变为对应状态时
都会调用,改变状态后,多个回调函数都会调用,并不会自动停止.简而言之,就是只要 promise 改变了状态,All callback functions bound to it will be called and executed.
let p = new Promise((resolve, reject) => {
// resolve('ok');
reject('err');
});
console.log(p);
// 指定回调-1
p.then(value => {
console.log('I am the first callback:' + value);
}).catch(reason => {
console.log('I am the first callback:' + reason);
});
// 指定回调-2
p.then(value => {
console.log('I am the second callback:' + value);
}).catch(reason => {
console.log('I am the second callback:' + reason);
});
You can see the failure status,Both failure callbacks are calledcatchThe method is processed and returned,同理,成功时会调用thenThe same method returns the corresponding callback result.
问题三、改变 promise 状态和指定回调函数谁先谁后?
(1) 都有可能
Under normal circumstances, the state is changed first and then the callback is specified,But it is also possible to specify a callback before changing the state
- 先指定回调再改变状态(
异步
):先指定回调 => 再改变状态 => 改变状态后才进入异步队列执行回调函数 - 先改状态再指定回调(
同步
):改变状态 =>指定回调并马上执行
回调
(2) 如何先改状态再指定回调?
注意: 指定并不是执行
- ① 在执行器中直接调用 resolve()/reject() --> 同步操作
- ② 延迟更长时间才调用 then() -->在
.then()
这个方法外再包一层例如延时器这种方法,异步操作
(3) 什么时候才能得到数据?
- 如果
The callback specified first
, 那当状态发生改变时, 回调函数就会调用, 得到数据 - 如果
先改变的状态
, 那当指定回调时, 回调函数就会调用, 得到数据 - 也就是说只有当状态改变后才能得到数据
Below we give an example 先指定回调后改变状态 的小案例:
let p = new Promise((resolve, reject) => {
setTimeout(() => {
resolve('okk');
}, 1000);
});
const dp = p.then(value => {
console.log('The final callback result is :' + value);
},reason=>{
console.log(reason);
});
console.log(dp);
可以看到我们将pThe callback is assigned todp,and this caseDelayed changing state,So it is specifying the callback first,后改变状态,But the final result of the callback is still the output after the state has changed,由此可以得出结论:
只有当状态改变后才能得到数据
问题四、promise.then()返回的新 promise 的结果状态由什么决定?
答: 由 then() 指定的回调函数执行的结果决定
(1)如果抛出异常
, 新 promise 变为 rejected
, reason
为抛出的异常
(2)如果返回
的是非 promise
的任意值, 新 promise
变为 resolved
, value
为返回的值
(3)如果返回
的是另一个新 promise
, 此 promise
的结果就会成为新 promise
的结果
let p = new Promise((resolve, reject) => {
resolve('ok'); // 成功
});
// 执行then方法
let result = p.then(value => {
// console.log(value);
// 1. 抛出错误
// throw '出错了!'; // 失败 reject
// 2. 返回结果是非 Promise 类型的对象
// return 111; // 成功 fulfilled The result is the return value
// 3. 返回结果是 Promise 对象
return new Promise((resolve, reject) => {
reject('error了')
})
}, reason => {
console.warn(reason);
});
console.log(result);
有三种情况,It can be seen from the above case(第三种情况,The first two cases can be seen in the code comments,这里就不一一例举了),我们先把 promise 改变状态为
成功
,然后往then方法
里面传入失败状态
的 promise 对象,The final result is based onthen
The state of the object in it is determined.
问题五、promise 如何串连多个操作任务?
- promise 的
then()
返回一个新的 promise, 可以看成then()
的链式调用
- 通过
then 的链式调用
串连多个同步/异步任务,这样就能用then()
将多个同步或异步操作串联成一个同步队列
let p = new Promise((resolve, reject) => {
setTimeout(() => {
resolve('ok');
}, 1000);
});
p.then(value => {
return new Promise((resolve, reject) => {
resolve('success');
});
}).then(value => {
console.log(value);
}).then(value => {
console.log(value);
});
由上面可以得到,只有当
p
的状态变为成功'ok'
时,第一个then
The success callback will be executed,Then the result in the callback function'success'
,当then
的第一个回调promise 对象
成功时,will continue to the next callback,因为第一个then
的回调返回了一个promise 成功的对象,So his return value will be passed to the second onethen
的回调里面,所以第二个then
的回调 中会输出'success'
,但第二个then
的回调没有返回值,所以第三个then
回调输出undefined
.
问题六、promise 异常穿透
- 当使用
promise
的then 链式调用
时, 可以在最后指定失败的回调 - 前面任何操作出了异常, 都会Passed to the last failed callback catch() 中处理
可以在每个then()的第二个回调函数(reason)中进行err处理,也可以利用
异常穿透
特性,到最后用catch
去承接统一处理,两者一起用时,前者(reason)会生效
(因为reason
已经将其处理,就Will not penetrate further down),Can't get behindcatch
Here is a supplement to the previous knowledge points,then方法有Two arguments in the form of callback functions,前者(
value
)代表成功
的回调,后者(reason
)代表失败
的回调.
then 的第二个回调 reason
处理 err
如下:
let p = new Promise((resolve, reject) => {
setTimeout(() => {
resolve('ok');
// reject('err')
}, 1000);
});
p.then(value => {
console.log(111);
}).then(value => {
console.log(222);
}).then(value => {
throw '出错啦!'
return value; // Pass the failed value to the next onethen中
}).then (value => {
console.log(value);
}, reason => {
console.warn(reason); // 失败时回调
});
异常穿透
处理 err
方法如下:
let p = new Promise((resolve, reject) => {
setTimeout(() => {
resolve('ok');
}, 1000);
});
p.then(value => {
console.log(111);
}).then(value => {
console.log(222);
}).then(value => {
// console.log(333);
throw '出错啦!'
}).catch (reason => {
console.warn(reason);
});
You will end up with the following output
问题七、中断 promise 链
应用场景
:The second question above is known,当promise状态改变
时,All his chained calls will生效
,那如果我们有这个一个实际需求:我们有3个 then()
,If there is a conditional judgment,不符合第一个 then()
条件时,要直接中断链式调用,The call below is no longer run then()
,解决方法如下.
- 当使用 promise 的
then
链式调用时, 在中间中断
, 不再调用后面的回调函数 - 办法: 在回调函数中返回一个
pendding
状态的promise 对象
return new Promise(() => {});
// 返回一个pending状态的Promise对象
let p = new Promise((resolve, reject) => {
setTimeout(() => {
resolve('OK');
}, 1000);
});
p.then(value => {
console.log(111);
//有且只有一个方式
// 返回一个pending状态的Promise对象
return new Promise(() => {
});
}).then(value => {
console.log(222);
}).then(value => {
console.log(333);
}).catch(reason => {
console.warn(reason);
});
Authors: min
时间: 2022年7月26日
边栏推荐
- 图解MySQL内连接、外连接、左连接、右连接、全连接......太多了
- How to Steal $100 Million from the Perfect Smart Contract
- 【cartographer ros】十: 延时和误差分析
- 我是如何保护 70000 ETH 并赢得 600 万漏洞赏金的
- 回归预测 | MATLAB实现TPA-LSTM(时间注意力注意力机制长短期记忆神经网络)多输入单输出
- Message queue interview latest finishing (2022)
- 上周热点回顾(7.25-7.31)
- Glassmorphism design style
- 【cartographer ros】10: Delay and error analysis
- Browser shortcut keys
猜你喜欢
小程序毕设作品之微信美食菜谱小程序毕业设计成品(1)开发概要
Small application project works WeChat gourmet recipes applet graduation design of finished product (1) the development profile
Qt 支持HEIC/HEIF格式图片
jmeter
shell脚本------条件测试 if语句和case分支语句
.NET深入解析LINQ框架(三:LINQ优雅的前奏)
Android Security and Protection Policy
The meaning and trigger conditions of gc
解决vscode输入! 无法快捷生成骨架(新版vscode快速生成骨架的三种方法)
Message queue interview latest finishing (2022)
随机推荐
7. SAP ABAP OData 服务如何支持 $orderby (排序)操作
Guangyu Mingdao was selected into the list of pilot demonstration projects for the development of digital economy industry in Chongqing in 2022
【cartographer ros】10: Delay and error analysis
世界第4疯狂的科学家,在103岁生日那天去世了
跨域网络资源文件下载
可视化——Superset安装与部署
一文说明白ECDSA spec256k1 spec256r1 EdDSA ed25519千丝万缕的关系
已解决(pip安装库报错)Consider using the-- user option or check the permissions.
深度学习 | MATLAB实现GRU门控循环单元gruLayer参数设定
Promise学习(三)Promise的几个关键性问题 -- 状态改变、执行顺序与机制、多任务串联、异常穿透、中断promise链
MySQL 必现之死锁
CTFshow,命令执行:web33
将本地项目推送到远程仓库
【钛晨报】国家统计局:7月制造业PMI为49%;玖富旗下理财产品涉嫌欺诈,涉及390亿元;国内航线机票燃油附加费8月5日0时起下调
昇思大模型体验平台初体验——以小模型LeNet为例
进制与转换、关键字
AI篮球裁判火了,走步算得特别准,就问哈登慌不慌
Introduction to STM32 development Introduce IIC bus, read and write AT24C02 (EEPROM) (using analog timing)
Mysql index related knowledge review one
What are the common API security flaws?