当前位置:网站首页>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)
})
边栏推荐
- Web3's need for law
- [node learning notes] the chokidar module realizes file monitoring
- Qt蓝牙:QBluetoothDeviceInfo
- Matlb| economic scheduling with energy storage, opportunity constraints and robust optimization
- C # / vb. Net supprime le filigrane d'un document word
- MySQL
- Redis入门完整教程:复制原理
- STM32 project -- Topic sharing (part)
- Common fitting models and application methods of PCL
- QPushButton-》函数精解
猜你喜欢
Niuke programming problem -- double pointer of 101 must be brushed
【Socket】①Socket技术概述
C#/VB. Net to delete watermarks in word documents
Classify the features of pictures with full connection +softmax
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?
What management points should be paid attention to when implementing MES management system
Software testing -- common assertions of JMeter interface testing
KYSL 海康摄像头 8247 h9 isapi测试
Redis入门完整教程:客户端案例分析
运维管理系统有哪些特色
随机推荐
What are the characteristics of the operation and maintenance management system
MES管理系统的应用和好处有哪些
wzoi 1~200
Kubernetes源码分析(二)----资源Resource
MetaForce原力元宇宙佛萨奇2.0智能合约系统开发(源码部署)
一本揭秘字节万台节点ClickHouse背后技术实现的白皮书来了!
Oracle中日期的使用方法实例
6-6漏洞利用-SSH安全防御
leetcode:736. LISP syntax parsing [flowery + stack + status enumaotu + slots]
wzoi 1~200
软件测试——Jmeter接口测试之常用断言
The third season of ape table school is about to launch, opening a new vision for developers under the wave of going to sea
C # / vb. Net supprime le filigrane d'un document word
Douban average 9 x. Five God books in the distributed field!
What management points should be paid attention to when implementing MES management system
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?
Contribution of Writing Series
Draco - gltf model compression tool
MySQL - common functions - string functions
数字滚动增加效果