当前位置:网站首页>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)
})
边栏推荐
- 海外媒体宣发.国内媒体发稿要注意哪些问题?
- Alibaba Cloud Jia Zhaohui: Cloud XR platform supports Bizhen Technology to present a virtual concert of national style sci-fi
- 48 the mysql database
- Configuration swagger
- search--09
- Servlet---解决post请求中中文乱码问题
- LeetCode中等题之颠倒字符串中的单词
- 7. Instant-ngp
- LeetCode 24. Swap nodes in linked list pairwise
- LeetCode 61. Rotating linked list
猜你喜欢
随机推荐
多线程下自旋锁设计基本思想
You have a Doubaqiong thesaurus, please check it
爱可可AI前沿推介(8.10)
So delicious!Since using this interface artifact, my team efficiency has increased by 60%!
CURRENT_TIMESTAMP(6) 函数是否存在问题?
如何让别人看不懂你的 JS 代码?把你当大佬!
dedecms支持Word内容一键导入
16、Pytorch Lightning入门
【论文+代码】PEBAL/Pixel-wise Energy-biased Abstention Learning for Anomaly Segmentation on Complex Urban Driving Scenes(复杂城市驾驶场景异常分割的像素级能量偏置弃权学习)
[List merge] Combine multiple lists into one list
可视化服务编排在金融APP中的实践
用低代码驱动IT现代化
Overseas media publicity. What problems should domestic media pay attention to?
wirshark 常用操作及 tcp 三次握手过程实例分析
Behind IDC's No. 1 position, what kind of "video cloud" is Alibaba Cloud building?
Samsung plans to start producing semiconductor components in Vietnam in 2023
StarRocks on AWS Review | Data Everywhere Series Event Shenzhen Station ended successfully
Servlet---解决post请求中中文乱码问题
中科院深圳先进技术院合成所赵国屏院士组2022年招聘启事
“68道 Redis+168道 MySQL”精品面试题(带解析)