当前位置:网站首页>Detailed explanation of es6-promise object
Detailed explanation of es6-promise object
2022-08-10 12:56:00 【forwardMyLife】
1.promise简介
promise是es6A new object in ,It is mainly used to obtain the result of the success or failure of an asynchronous operation.promise是jsCore objects in asynchronous programming,es8中await和async也是基于promise实现的
promise对象有3种状态,
| 状态 | 描述 |
|---|---|
| pending | 等待中,还未执行完 |
| resolved | 执行成功 |
| rejected | 执行失败 |
状态变更:只有2种
pending => resolved
pending => rejected
2.promise的优点
避免回调地狱,promise对象执行完后,可以在then方法,或catch方法中,获取结果,thenmethod will also return onepromise对象(Even if it returns a normal object itself, it is eventually wrappedpromise对象)
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 ......");
promiseThe object's argument is a single arrow function,箭头函数2The input parameter is2个函数,resolve,reject,Status change for success or failure.
resolve的结果为thenThe first arrow function of the methodvalue参数,
如果then设置了第二个参数,则promise在被rejector if an exception is thrownreason的箭头函数.
then也会返回一个新的promise对象.
thenThe method will wait until the synchronized block of code is executed,才会执行.而promiseThe instantiated code is executed synchronously.
The entire execution is asynchronous.
The result of executing the above code is as follows:
4.promise常用静态方法
1.promise的对象方法(p1,p2,p3为promise的实例对象)
Promise.all()并发处理多个异步任务,所有任务都执行完成才能得到结果
Promise.all( [p1,p2,p3] ) .then ( (result) => {
console.info (result);
})
2.Promise.race()并发处理多个异步任务,The result is returned as long as one task completes
Promise.all()并发处理多个异步任务,所有任务都执行完成才能得到结果
Promise.race ( [p1,p2,p3] ).then ( (result)=>{
console.log (result)
})
边栏推荐
猜你喜欢
随机推荐
娄底干细胞制备实验室建设须知要求
加密游戏:游戏的未来
What are the five common data types of Redis?What is the corresponding data storage space?Take you to learn from scratch
娄底农产品检验实验室建设指南盘点
【黑马早报】雷军称低谷期曾想转行开酒吧;拜登正式签署芯片法案;软银二季度巨亏230亿美元;北京市消协约谈每日优鲜...
实践为主,理论为辅!腾讯大佬MySQL高阶宝典震撼来袭!
可视化服务编排在金融APP中的实践
部署项目半途而废后续
Dining (web stream)
啥?他一个人写了个价值100万的软件,却用来开源了!
【iOS】Organization of interviews
自定义过滤器和拦截器实现ThreadLocal线程封闭
【mysql索引实现原理】
Diary 16
Excel function formulas - LOOKUP function
Chapter 5 virtual memory
Common examples of regular expressions
人脸考勤是选择人脸比对1:1还是人脸搜索1:N?
爱可可AI前沿推介(8.10)
ArcMAP出现-15的问题无法访问[Provide your license server administrator with the following information:Err-15]








