当前位置:网站首页>es6-promise对象详解
es6-promise对象详解
2022-08-10 12:07:00 【forwardMyLife】
1.promise简介
promise是es6中新出的一个对象,主要用来获取异步操作成功或者失败的结果。promise是js异步编程中的核心对象,es8中await和async也是基于promise实现的
promise对象有3种状态,
状态 | 描述 |
---|---|
pending | 等待中,还未执行完 |
resolved | 执行成功 |
rejected | 执行失败 |
状态变更:只有2种
pending => resolved
pending => rejected
2.promise的优点
避免回调地狱,promise对象执行完后,可以在then方法,或catch方法中,获取结果,then方法中也会返回一个promise对象(即便本身返回的是普通对象最终也被包装成promise对象)
3.promise对象的创建
let promise = new Promise((resovle,reject)=>{
console.info("create promise object");
setTimeout(() => {
resovle("ok");
});
}).then(value=>{
console.info("successed to promise,returned value:"+value);
},reason=>{
console.info("failed to execute promise,reason"+reason);
}).catch(reason=>{
console.error(`failed to reason:${
reason}`);
});;
promise.then(value=>{
console.info("then:"+value);
});
console.info("end js ......");
promise对象的入参单个箭头函数,箭头函数2个入参为2个函数,resolve,reject,用于成功或失败的状态变更。
resolve的结果为then方法的第一个箭头函数的value参数,
如果then设置了第二个参数,则promise在被reject或抛出异常的情况下会执行reason的箭头函数。
then也会返回一个新的promise对象。
then方法中会等到同步代码块执行完,才会执行。而promise实例化的代码是同步执行的。
整个执行是异步的。
如上述代码执行结果如下:
4.promise常用静态方法
1.promise的对象方法(p1,p2,p3为promise的实例对象)
Promise.all()并发处理多个异步任务,所有任务都执行完成才能得到结果
Promise.all( [p1,p2,p3] ) .then ( (result) => {
console.info (result);
})
2.Promise.race()并发处理多个异步任务,只要有一个任务完成就会返回结果
Promise.all()并发处理多个异步任务,所有任务都执行完成才能得到结果
Promise.race ( [p1,p2,p3] ).then ( (result)=>{
console.log (result)
})
边栏推荐
- 「网络架构」网络代理第一部分: 代理概述
- So delicious!Since using this interface artifact, my team efficiency has increased by 60%!
- LeetCode 237. Delete a node in a linked list
- 百度用户产品流批一体的实时数仓实践
- three.js blur glass effect
- search--09
- Microchip launched a high-performance 77GHz millimeter-wave radar chip, and has received tens of thousands of orders before mass production
- 查看 CUDA cudnn 版本 & 测试 cuda 和 cudnn 有效性「建议收藏」
- 爱可可AI前沿推介(8.10)
- 百度用户产品流批一体的实时数仓实践
猜你喜欢
three.js模糊玻璃效果
阿里云贾朝辉:云XR平台支持彼真科技呈现国风科幻虚拟演唱会
IDC第一的背后,阿里云在打造怎样的一朵“视频云”?
神经网络学习-正则化
2022年8月中国数据库排行榜:openGauss重夺榜眼,PolarDB反超人大金仓
A detailed explanation of implementation api embed
【论文+代码】PEBAL/Pixel-wise Energy-biased Abstention Learning for Anomaly Segmentation on Complex Urban Driving Scenes(复杂城市驾驶场景异常分割的像素级能量偏置弃权学习)
CV复习:空洞卷积
Chapter 5 virtual memory
如何培养ui设计师的设计思维?
随机推荐
“68道 Redis+168道 MySQL”精品面试题(带解析)
厚积薄发!安全狗再次获得科技成果转化认证!
AICOCO AI Frontier Promotion (8.10)
协程与任务
一文详解 implementation api embed
【list合并】多个list合并为一个list
mpf6_Time Series Data_quandl_correct kernel PCA_AIC_BIC_trend_log_return_seasonal_decompose_sARIMAx_ADFull
LeetCode 445. Adding Two Numbers II
人脸考勤是选择人脸比对1:1还是人脸搜索1:N?
An enhanced dynamic packet buffer management.论文核心部分
基础 | batchnorm原理及代码详解
LeetCode 146. LRU Cache
Configuration swagger
Does face attendance choose face comparison 1:1 or face search 1:N?
MySQL索引的B+树到底有多高?
dedecms支持Word内容一键导入
正则表达式常用示例
培训机构学习费用是多少呢?
IDC第一的背后,阿里云在打造怎样的一朵“视频云”?
search--01