当前位置:网站首页>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)
})边栏推荐
- HAVE FUN | “飞船计划”活动最新进展
- PSINS中19维组合导航模块sinsgps详解(初始赋值部分)
- Remember the problem analysis of oom caused by a Jap query
- Redis入门完整教程:复制拓扑
- Static proxy of proxy mode
- Unity custom webgl packaging template
- Django数据库(SQlite)基本入门使用教程
- 实施MES管理系统时,哪些管理点是需要注意的
- 【软件测试】最全面试问题和回答,全文背熟不拿下offer算我输
- Application analysis of face recognition
猜你喜欢

一文读懂Faster RCNN

实施MES管理系统时,哪些管理点是需要注意的

Cloud Mail . NET Edition

Software testing -- common assertions of JMeter interface testing

牛客编程题--必刷101之双指针篇

从零安装Redis

How to write test cases for test coupons?
Django database (SQLite) basic introductory tutorial

Statistics of radar data in nuscenes data set

Hash table and full comments
随机推荐
【Socket】①Socket技术概述
数字滚动增加效果
[node learning notes] the chokidar module realizes file monitoring
Have fun | latest progress of "spacecraft program" activities
NuScenes数据集关于Radar数据的统计
How to design interface test cases? Teach you a few tips to draft easily
Kubernetes源码分析(二)----资源Resource
Oracle中日期的使用方法实例
Summer Challenge database Xueba notes (Part 2)~
牛客编程题--必刷101之双指针篇
MySQL - common functions - string functions
QT常见概念-1
Redis入门完整教程:复制原理
记一次JAP查询导致OOM的问题分析
Redis入门完整教程:问题定位与优化
实施MES管理系统时,哪些管理点是需要注意的
Difference and the difference between array and array structure and linked list
What are the characteristics of the operation and maintenance management system
Ali yunyili: how does yunyuansheng solve the problem of reducing costs and improving efficiency?
Draco - gltf model compression tool