当前位置:网站首页>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)
})
边栏推荐
- Excel函数公式大全—LOOKUP函数
- IDC第一的背后,阿里云在打造怎样的一朵“视频云”?
- CLIP还能做分割任务?哥廷根大学提出一个使用文本和图像prompt,能同时作三个分割任务的模型CLIPSeg,榨干CLIP能力...
- LT8911EXB MIPI CSI/DSI to EDP signal conversion
- 7、Instant-ngp
- 「网络架构」网络代理第一部分: 代理概述
- ASP.NET Core依赖注入系统学习教程:ServiceDescriptor(服务注册描述类型)
- Accumulated and thin hair!Safety Dog has once again obtained the certification of scientific and technological achievements transformation!
- 一文详解 implementation api embed
- Polygon zkEVM工具——PIL和CIRCOM
猜你喜欢
随机推荐
Diary 16
啥?他一个人写了个价值100万的软件,却用来开源了!
MySQL索引的B+树到底有多高?
【论文+代码】PEBAL/Pixel-wise Energy-biased Abstention Learning for Anomaly Segmentation on Complex Urban Driving Scenes(复杂城市驾驶场景异常分割的像素级能量偏置弃权学习)
camshift实现目标跟踪
three.js模糊玻璃效果
Microchip launched a high-performance 77GHz millimeter-wave radar chip, and has received tens of thousands of orders before mass production
MySQL面试题——MySQL常见查询
LeetCode 92. Reverse Linked List II
实践为主,理论为辅!腾讯大佬MySQL高阶宝典震撼来袭!
CodeForces - 628D (digital dp)
StarRocks on AWS 回顾 | Data Everywhere 系列活动深圳站圆满结束
Configuration swagger
第5章 虚拟存储器
iTextSharp 使用详解
7. Instant-ngp
基础 | batchnorm原理及代码详解
LT8911EXB MIPI CSI/DSI to EDP signal conversion
IM即时通讯开发WebSocket从入门到精通
Threshold-based filtering buffer management scheme in a shared buffer packet switch core part of the paper