当前位置:网站首页>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 onthenThe 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'时,第一个thenThe 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日
边栏推荐
- Introduction to data warehouse layering (real-time data warehouse architecture)
- 使用KeyStore生成证书
- [Cloud Residency Co-Creation] Huawei Cloud Global Scheduling Technology and Practice of Distributed Technology
- ClickHouse多种安装方式
- SAP ABAP OData 服务如何支持 $orderby (排序)操作试读版
- Browser shortcut keys
- 深度学习 | MATLAB实现一维卷积神经网络convolution1dLayer参数设定
- 小程序毕设作品之微信美食菜谱小程序毕业设计成品(2)小程序功能
- Message queue interview latest finishing (2022)
- experiment....
猜你喜欢

回归预测 | MATLAB实现TPA-LSTM(时间注意力注意力机制长短期记忆神经网络)多输入单输出

Golang内存分析工具gctrace和pprof实战

MacOS下postgresql(pgsql)数据库密码为什么不需要填写或可以乱填写

ClickHouse多种安装方式

利用正则表达式的回溯实现绕过

小程序毕设作品之微信美食菜谱小程序毕业设计成品(4)开题报告

Google Earth Engine APP——15行代码搞定一个inspector高程监测APP

基于CAP组件实现补偿事务与消息幂等性

Promise学习(一)Promise是什么?怎么用?回调地狱怎么解决?

DBPack SQL Tracing 功能及数据加密功能详解
随机推荐
Custom Types - Enums, Unions
CTFshow,命令执行:web34、35、36
小程序毕设作品之微信美食菜谱小程序毕业设计成品(4)开题报告
WPF 截图控件之绘制箭头(五)「仿微信」
jmeter
机器学习 | MATLAB实现支持向量机回归RegressionSVM参数设定
报告:想学AI的学生数量已涨200%,老师都不够用了
MTK6225-紧急电话
MySQL常用语句总结
ModelArts-based object detection YOLOv3 practice [play with HUAWEI CLOUD]
Endorsed in 2022 years inventory | product base, science and technology, guangzhou automobile group striding forward
Pve delete virtual machine "for a collection"
Why Metropolis–Hastings Works
从零开始Blazor Server(4)--登录系统
How to Steal $100 Million from the Perfect Smart Contract
Introduction to data warehouse layering (real-time data warehouse architecture)
【软件架构模式】MVVM模式和MVC模式区别
广域铭岛入选2022年重庆市数字经济产业发展试点示范项目名单
Mini Program Graduation Works WeChat Food Recipes Mini Program Graduation Design Finished Products (4) Opening Report
Cross-domain network resource file download