当前位置:网站首页>ES6中的Promise
ES6中的Promise
2022-07-20 12:56:00 【我拿青春赌未来~】
1:定义
Promise是异步编程的一种解决方案,可以替代传统的解决方案--回调函数和事件。ES6统一了用法,并原生提供了Promise对象。作为对象,Promise有一下两个特点:
(1)对象的状态不受外界影响。
Promise对象代表一个异步操作,有三种状态:pending(进行中)、fulfilled(已成功)和rejected(已失败)。只有异步操作的结果,可以决定当前是哪一种状态,任何其他操作都无法改变这个状态。这也是Promise这个名字的由来,它的英语意思就是“承诺”,表示其他手段无法改变。
(2)一旦状态改变了就不会在变,也就是说任何时候Promise都只有一种状态。
Promise对象的状态改变,只有两种可能:从pending变为fulfilled和从pending变为rejected。只要这两种情况发生,状态就凝固了,不会再变了,会一直保持这个结果,这时就称为 resolved(已定型)。
2:三种状态
Pending状态(进行中)Fulfilled状态(已成功) Rejected状态(已失败)
一旦发生改变就只有一种状态:Pending -> Fulfilled Pending -> Rejected。
3:基本用法
Resolve,用来接收完成状态,reject用来接收失败的状态。
var promise = new Promise(function(resolve,reject){
let flag = true;
if(flag){
resolve('状态:执行成功!');
}else{
reject("状态:执行失败!");
}
})
promise.then(function(resolve){
console.log(resolve);
},function(reject){
console.log(reject);
})
说明:then方法可以接受两个回调函数作为参数。第一个回调函数是Promise对象的状态变为resolved时调用,第二个回调函数是Promise对象的状态变为rejected时调用。这两个函数都是可选的,不一定要提供。它们都接受Promise对象传出的值作为参数。
4:模拟异步
模拟未来即将发生的代码。
function timeout(ms){
return new Promise(function(relove,reject){
setTimeout(()=>{
console.log('程序'+ms +'毫秒后打印!');
},ms);
})
}
timeout(3000);
5:执行步骤
function timeout(ms){
console.log(2);
return new Promise(function(relove,reject){
setTimeout(()=>{
console.log(3);
relove(4);
},ms);
})
}
console.log(1);
let res = timeout(3000);
res.then(relove=>{
console.log(relove);
})
说明:Promise 新建后立即执行,所以首先输出的是Promise。然后,then方法指定的回调函数,将在当前脚本所有同步任务执行完才会执行,所以4最后输出。
6:封装ajax
const sendajax = function(url){
return new Promise(function(reslove,reject){
//创建对象
const o = new XMLHttpRequest();
o.open('GET',url);//初始化
o.send();//发送
//接收状态 绑定事件
o.onreadystatechange = function(){
if(o.readyState === 4){ //标识请求发送结束
if(o.status>=200 && o.status<300){//
reslove(o.response);
}else{
reject(o.status);//失败的状态码
}
}
}
})
}
let test = sendajax('https://api.apiopen.top/getJoke');
test.then(function(value){
console.log(value);
},function(reason){
console.log(reason);
})
7:Proimse.prototype.then
Promise 实例具有then方法,也就是说,then方法是定义在原型对象Promise.prototype上的。它的作用是为 Promise 实例添加状态改变时的回调函数。then方法的第一个参数是resolved状态的回调函数,第二个参数是rejected状态的回调函数,参数可选。
then方法返回的是一个新的Promise实例(注意,不是原来那个Promise实例)。因此可以采用链式写法,即then方法后面再调用另一个then方法。根据这一特性我们可以采用链式
方法:
function sayhi(){
let mypromise = new Promise(function(resolve,reject){
let str = "hello world";
resolve(str);
})
return mypromise;
}
sayhi().then(function(value){
console.log(value);
return value;
}).then(function(value){
console.log(value+2);
return value;
})
8:Promise.prototype.catch()
Promise.prototype.catch()方法是.then(null, rejection)或.then(undefined, rejection)的别名,用于指定发生错误时的回调函数。
let myfun = function(){
let mypromise = new Promise(function(resolve,reject){
reject('错误');
})
return mypromise;
}
//发生错误的时捕获
myfun().catch(function(e){
console.error(e);
});
边栏推荐
- 马斯克回应是否会将大脑上传到云端:Already did it!
- Four redis cluster schemes you must know and their advantages and disadvantages
- SAP Spartacus 服务器端渲染的三种可能情形
- Realization of commodity bargaining function
- Point cloud format reading and saving
- 利用postman进行接口测试并发送带cookie请求的方法
- AD活动目录和域网络
- How to query and modify parameter status values
- 除了定时器,真的没法在Simulation Node 类型的CAPL节点中实现延时了吗?
- Redis在Centos7上的安装部署[通俗易懂]
猜你喜欢
CAPL 脚本打印函数 write ,writeEx ,writeLineEx ,writeToLog ,writeToLogEx ,writeDbgLevel 你真的分的清楚什么情况下用哪个吗?
【28. 最大异或对】
Avec la sortie de HongMeng 3.0, la fusion Multi - écrans a progressé régulièrement, mais Google a subi une nouvelle chute
There are 450million 5g network users and more than 900million 5g package users. Why are users still unwilling to accept 5g?
懒到骨子里了,我在CSDN写文章都懒得自己写了,基于selenium模拟写文章
海思多媒体芯片选型
Dynamic and static libraries (.So/dll,.A/lib)
物联网标准体系框架
玫瑰通行证发放中!
限制input框中的输入类型及长度
随机推荐
SAP Spartacus 服务器端渲染的三种可能情形
程序员看的JPEG图像压缩介绍(多图慎入)
同步原语:锁
gcc入门手册
从0到1 拿下C语言—程序结构及使用示例
If you can't understand the character code, hit me! (ASCII,Unicode,Utf-8,GB2312…)
Installation and deployment of redis on centos7 [easy to understand]
Double shutter Technology
如何查询、修改参数状态值
CAPL 脚本打印函数 write ,writeEx ,writeLineEx ,writeToLog ,writeToLogEx ,writeDbgLevel 你真的分的清楚什么情况下用哪个吗?
commonJS导出导入
Selenium grid installation
转:情绪的内耗,才是你人生低效的最大根源
UML顺序图/序列图/时序图
A strange problem in the running process of LoadRunner
Repeaters, hubs, bridges, switches, routers
Spatial noise reduction and time domain noise reduction
Examples illustrate the division basis of code segment (.Text), data segment (.Data), BSS segment, read-only data segment (.Rodata) and stack
【c ++ primer 笔记】第8章 IO库
三维数据(channel在第2维)-四维数据(输入到pooling层之前,channel在第一维)-三维数据(channel在第2维)