当前位置:网站首页>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)
})
边栏推荐
- Threshold-based filtering buffer management scheme in a shared buffer packet switch论文核心部分
- Crypto Gaming: The Future of Gaming
- LT8911EXB MIPI CSI/DSI to EDP signal conversion
- LeetCode 146. LRU Cache
- search--09
- An enhanced dynamic packet buffer management. The core part of the paper
- 【集合】HashSet和ArrayList的查找Contains()时间复杂度
- 蚂蚁金服+拼多多+抖音+天猫(技术三面)面经合集助你拿大厂offer
- LeetCode中等题之颠倒字符串中的单词
- CURRENT_TIMESTAMP(6) 函数是否存在问题?
猜你喜欢

AICOCO AI Frontier Promotion (8.10)

加密游戏:游戏的未来

阿里架构师整理一份企业级SSM架构实战文档,让你熟悉底层原理

22年BATJ大厂必问面试题(复盘):JVM+微服务+多线程+锁+高并发

CURRENT_TIMESTAMP(6) 函数是否存在问题?

自定义过滤器和拦截器实现ThreadLocal线程封闭

一文详解 implementation api embed

StarRocks on AWS Review | Data Everywhere Series Event Shenzhen Station ended successfully

面试美团被问到了Redis,搞懂这几个问题,让你轻松吊打面试官

「网络架构」网络代理第一部分: 代理概述
随机推荐
娄底疾控中心实验室设计理念说明
CV复习:空洞卷积
漏洞管理计划的未来趋势
47Haproxy Cluster
phpstrom 快速注释:
Chapter 5 virtual memory
Solve the idea that unit tests cannot use Scanner
Common examples of regular expressions
动态规划之最长回文子串
odps sql 不支持 unsupported feature CREATE TEMPORARY
一文详解 implementation api embed
An enhanced dynamic packet buffer management.论文核心部分
Keithley DMM7510精准测量超低功耗设备各种运作模式功耗
人脸考勤是选择人脸比对1:1还是人脸搜索1:N?
Configuration swagger
LeetCode 24. Swap nodes in linked list pairwise
ArcMAP出现-15的问题无法访问[Provide your license server administrator with the following information:Err-15]
16、Pytorch Lightning入门
An enhanced dynamic packet buffer management. The core part of the paper
iTextSharp 使用详解