当前位置:网站首页>Es6中Promise的使用
Es6中Promise的使用
2022-07-06 19:21:00 【这次我一定要赢】
一.Promise是什么?
Promise是一个构造函数,总共有三种状态 ,成功(fulfiled),失败(reject),等待(pending), 里面有两个参数resolve和reject。
代码:
const p1 = new Promise((resolve, reject) => {
})
二.Promise的api方法
1.then拿到成功之后状态的值。
2.catch捕获失败状态的值。
三.Promise用来干什么的?
来解决异步的问题,通常用到请求接口上。
(1)返回的是一个成功(fulfiled)的状态
代码:
const p1 = new Promise((resolve, reject) => {
resolve('成功的状态')
})
console.log(p1);
p1.then(res => {
console.log(res, '拿到接口返回的成功值');
})
成功的状态:
(2)返回的是一个失败(reject)的状态。
代码:
const p1 = new Promise((resolve, reject) => {
reject('失败的状态')
})
console.log(p1);
p1.then(res => {
console.log(res, '拿到接口返回的失败值');
})
失败的状态:
结论:
then是拿不到失败状态reject的值的。
这个时候我们来试试.catch
修改代码:
const p1 = new Promise((resolve, reject) => {
reject('失败的状态')
})
console.log(p1);
p1.catch(res => {
console.log(res, '拿到接口返回的成功值');
})
可以捕获。
(3) 等待(pending)的状态。
代码:
const p1 = new Promise((resolve, reject) => {
})
console.log(p1);
等待的状态:
(4)关联到实际api接口的调用
如:
1.用mockfast模拟一个接口
2.请求例子
<template>
<div class="">
<button @click="fn">发送get请求</button>
</div>
</template>
<script>
import axios from 'axios'
export default {
data(){return{
}},
name: '',
methods: {
fn(){
// alert('11111111')
axios({
method:'GET',
url:"https://www.fastmock.site/mock/f9834bca1c0604895ec164037a0590c6/api/test",
}).then(res=>console.log(res))
}
},
}
</script>
返回的结果:
请求失败的时候用.catch进行捕获,后端也会返回数据给前端。
如:
401 权限不够
404 参数错误
500 服务器错误 等
这个时候我们需要使用.catch进行捕获。
四.实际应用
(1)请求接口的方式也是一个异步的强求
<template>
<div class="">
<button @click="fn">发送get请求</button>
</div>
</template>
<script>
import axios from 'axios'
export default {
data(){return{
}},
name: '',
methods: {
fn(){
// alert('11111111')
const p1= axios({
method:'get',
url:"https://www.fastmock.site/mock/f9834bca1c0604895ec164037a0590c6/api/test",
})
console.log(p1,111111111111111111);
}
},
}
</script>
所以我们在平常的开发中可以用then或者catch来对接口的数据进行捕获。
(2).then和.catch一起使用
<template>
<div class="">
<button @click="fn">发送get请求</button>
</div>
</template>
<script>
import axios from 'axios'
export default {
data(){return{
}},
name: '',
methods: {
fn(){
// alert('11111111')
axios({
method:'get',
url:"https://www.fastmock.site/mock/f9834bca1c0604895ec164037a0590c6/api/test",
}).then(res=>console.log(res)).catch(reject=>console.log(reject))
}
},
}
</script>
五.替代方案async await
用Promise解决异步编程固然是没有问题的,如果要发送很多的请求呢?
请看下面的代码:
let a1 = new Promise((resolve, reject) => {
resolve('吃饭')
}).then(res => {
alert(res)
return new Promise((resolve, reject) => {
resolve('睡觉')
})
}).then(res => {
alert(res)
return new Promise((resolve, reject) => {
resolve('打豆豆')
})
}).then(res => alert(res))
如果是多个Promise看起来是不是非常的冗余。
解决的方案:
async和await
<SCript>
let a1 = new Promise((resolve) => {
resolve('吃饭')
})
let a2 = new Promise((resolve) => {
resolve('睡觉')
})
let a3 = new Promise((resolve) => {
resolve('打豆豆')
})
async function fn() {
const res1 = await a1
console.log(res1);
const res2 = await a2
console.log(res2);
const res3 = await a3
console.log(res3);
}
fn()
</SCript>
它的用法:
在最近一级的函数前面加上async
后面加上await进行接收就可以了
打印出的结果:
对比上面的结果是不是更加清晰一点。
六.用async修饰的函数是异步函数吗?
看如下代码:
async function fn() {
console.log(123);
}
console.log(fn());
打印出的结果:
是一个Promise对象,他代表只是一种状态。
证明里面不是异步
代码:
async function fn() {
console.log(123);
}
console.log(fn());
console.log(456);
如果这个函数是异步执行的输出的结果是 456 123
而实际的结果是:
所以它不代表的只是Promise的一种状态。
如果里面加上await呢?
代码:
<SCript>
async function fn() {
await console.log(123);
}
console.log(fn());
console.log(456);
</SCript>
得出结论
await后面的代码都是异步执行的。
综上所述:
1.用async修饰的函数里面并不是异步去执行的,只是变成Promise的一种状态。
2.在await后面的都是异步去执行的。
七.如何去中断一个Promise
抛出一个Pending的状态就可以了
代码:
new Promise((resolve, reject) => {
resolve(2)
}).then(res => {
// 中断
throw new Promise((resolve, reject) => {
})
return new Promise((resolve, reject) => {
resolve(3)
})
}).then(res => console.log(res))
八.Promise扩展api
(1)Promise.race
代码:
const a1 =
new Promise((resolve, reject) => {
setTimeout(() => {
resolve(20)
}, 2000);
})
const a2 =
new Promise((resolve, reject) => {
setTimeout(() => {
resolve(100)
}, 1000);
})
const a3 =
new Promise((resolve, reject) => {
setTimeout(() => {
resolve(30)
}, 3000);
})
const p1 = Promise.race([a1, a2, a3]).then(res => alert(res))
谁用的时间最短就执行谁。
结果肯定执行100。
中途有reject也是一样的,不管成功失败谁的时间短。
const a1 =
new Promise((resolve, reject) => {
setTimeout(() => {
reject(20)
}, 2000);
})
const a2 =
new Promise((resolve, reject) => {
setTimeout(() => {
resolve(100)
}, 1000);
})
const a3 =
new Promise((resolve, reject) => {
setTimeout(() => {
resolve(30)
}, 3000);
})
const p1 = Promise.race([a1, a2, a3]).then(res => alert(res), err => alert(err))
(2)Promise.all
相比于赛跑机制这个是一起去执行的。
const a1 = Promise.resolve(10)
const a2 = Promise.resolve(20)
const a3 = Promise.reject(30)
const p1 = Promise.all([a1, a2, a3]).then(res => console.log(res), err =>
console.log(err))
用[]包裹起来,等里面的执行完毕在拿到相应的实例
如果中途有错误会立马进行停止。
这个可以在发送多个异步请求的时候使用。发送前有个loading加载的效果。
等异步发送完毕后加载结束。
注意这个和异步的时间没有关系,和包裹的循序有关系。
const a1 = Promise.resolve(10)
const a2 = Promise.resolve(20)
const a3 = Promise.resolve(30)
const p1 = Promise.all([a2, a1, a3]).then(res => console.log(res), err => console.log(err))
输出的结果:
[10,20,30]
九.Promise.resolve和Promise.reject
Promise.resolve(2).then(res => console.log(res))
Promise.reject(3).catch(reject => console.log(reject))
它的等价:
Promise.resolve(2).then(res => console.log(res))
new Promise((resolve, reject) => {
resolve(2)
})
Promise.reject(3).then(reject=> console.log(reject))
new Promise((resolve, reject) => {
reject(3)
})
边栏推荐
- CDB PDB user rights management
- 安全交付工程师
- 测试优惠券要怎么写测试用例?
- What management points should be paid attention to when implementing MES management system
- Django database (SQLite) basic introductory tutorial
- Summary of basic debugging steps of S120 driver
- Examples of how to use dates in Oracle
- MetaForce原力元宇宙佛萨奇2.0智能合约系统开发(源码部署)
- [software test] the most complete interview questions and answers. I'm familiar with the full text. If I don't win the offer, I'll lose
- Five reasons for clothing enterprises to deploy MES management system
猜你喜欢
Pioneer of Web3: virtual human
Google Earth engine (GEE) -- 1975 dataset of Landsat global land survey
NuScenes数据集关于Radar数据的统计
Redis入門完整教程:問題定比特與優化
Argo workflows source code analysis
MMDetection3D加载毫米波雷达数据
Draco - gltf model compression tool
电气工程及其自动化
The annual salary of general test is 15W, and the annual salary of test and development is 30w+. What is the difference between the two?
Niuke programming problem -- double pointer of 101 must be brushed
随机推荐
The so-called consumer Internet only matches and connects industry information, and does not change the industry itself
MMDetection3D加载毫米波雷达数据
写作系列之contribution
The 8 element positioning methods of selenium that you have to know are simple and practical
The third season of ape table school is about to launch, opening a new vision for developers under the wave of going to sea
How to build a 32core raspberry pie cluster from 0 to 1
Digital scrolling increases effect
Convert widerperson dataset to Yolo format
Andrews - multimedia programming
Lombok makes the pit of ⽤ @data and @builder at the same time
Cloud Mail . NET Edition
Ali yunyili: how does yunyuansheng solve the problem of reducing costs and improving efficiency?
Examples of how to use dates in Oracle
QT common Concepts-1
Metaforce force meta universe fossage 2.0 smart contract system development (source code deployment)
Kubernetes源码分析(二)----资源Resource
测试优惠券要怎么写测试用例?
Go swagger use
unity webgl自适应网页尺寸
Number theory --- fast power, fast power inverse element