当前位置:网站首页>Use of promise in ES6
Use of promise in ES6
2022-07-07 02:52:00 【I must win this time】
One .Promise What is it? ?
Promise It's a constructor , There are three states , success (fulfiled), Failure (reject), wait for (pending), There are two parameters resolve and reject.
Code :
const p1 = new Promise((resolve, reject) => {
})
Two .Promise Of api Method
1.then Get the value of the status after success .
2.catch Capture the value of the failed state .
3、 ... and .Promise For what ?
To solve the problem of asynchrony , It is usually used on the request interface .
(1) Back to a success (fulfiled) The state of
Code :
const p1 = new Promise((resolve, reject) => {
resolve(' The state of success ')
})
console.log(p1);
p1.then(res => {
console.log(res, ' Get the success value returned by the interface ');
})
The state of success :
(2) Back to a Failure (reject) The state of .
Code :
const p1 = new Promise((resolve, reject) => {
reject(' Failed state ')
})
console.log(p1);
p1.then(res => {
console.log(res, ' Get the failure value returned by the interface ');
})
Failed state :
Conclusion :
then Is unable to get the failure status reject The value of the .
At this time, let's try .catch
Modify the code :
const p1 = new Promise((resolve, reject) => {
reject(' Failed state ')
})
console.log(p1);
p1.catch(res => {
console.log(res, ' Get the success value returned by the interface ');
})
Can capture .
(3) wait for (pending) The state of .
Code :
const p1 = new Promise((resolve, reject) => {
})
console.log(p1);
The state of waiting :
(4) Relate to actual api Interface call
Such as :
1. use mockfast Simulate an interface
2. Request example
<template>
<div class="">
<button @click="fn"> send out get request </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>
The result returned :
Use when the request fails .catch Capture , The back end will also return data to the front end .
Such as :
401 Not enough permissions
404 Parameter error
500 Server error etc.
We need to use .catch Capture .
Four . The practical application
(1) The way of requesting interfaces is also an asynchronous requirement
<template>
<div class="">
<button @click="fn"> send out get request </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>
So we can use then perhaps catch To capture the data of the interface .
(2).then and .catch Use it together
<template>
<div class="">
<button @click="fn"> send out get request </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>
5、 ... and . Alternatives async await
use Promise There is certainly no problem in solving asynchronous programming , What if you have to send a lot of requests ?
Look at the code below :
let a1 = new Promise((resolve, reject) => {
resolve(' having dinner ')
}).then(res => {
alert(res)
return new Promise((resolve, reject) => {
resolve(' sleep ')
})
}).then(res => {
alert(res)
return new Promise((resolve, reject) => {
resolve(' Doudou ')
})
}).then(res => alert(res))
If more than one Promise Does it seem very redundant .
solution :
async and await
<SCript>
let a1 = new Promise((resolve) => {
resolve(' having dinner ')
})
let a2 = new Promise((resolve) => {
resolve(' sleep ')
})
let a3 = new Promise((resolve) => {
resolve(' Doudou ')
})
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>
Its usage :
Add async
Followed by await Just receive
Printed results :
Is it clearer to compare the above results .
6、 ... and . use async Is the modified function an asynchronous function ?
Look at the code below :
async function fn() {
console.log(123);
}
console.log(fn());
Printed results :
It's a Promise object , He represents only a state .
Prove that it is not asynchronous
Code :
async function fn() {
console.log(123);
}
console.log(fn());
console.log(456);
If this function is executed asynchronously, the output result is 456 123
And the actual result is :
So it doesn't just mean Promise A state of being .
If you add await Well ?
Code :
<SCript>
async function fn() {
await console.log(123);
}
console.log(fn());
console.log(456);
</SCript>
Come to the conclusion
await The following code is executed asynchronously .
in summary :
1. use async Modified functions are not executed asynchronously , It's just becoming Promise A state of being .
2. stay await The latter are executed asynchronously .
7、 ... and . How to interrupt a Promise
Throw a Pending The state of the can be
Code :
new Promise((resolve, reject) => {
resolve(2)
}).then(res => {
// interrupt
throw new Promise((resolve, reject) => {
})
return new Promise((resolve, reject) => {
resolve(3)
})
}).then(res => console.log(res))
8、 ... and .Promise Expand api
(1)Promise.race
Code :
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))
Whoever takes the shortest time will execute .
The result must be 100.
Halfway there reject It's the same , No matter who succeeds or fails, the time is short .
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
Compared with the racing mechanism, this is implemented together .
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))
use [] Wrap it up , When the execution inside is completed, get the corresponding instance
If there is an error in the way, it will stop immediately .
This can be used when sending multiple asynchronous requests . Before sending loading The effect of loading .
After asynchronous sending, loading ends .
Note that this has nothing to do with asynchronous time , It has something to do with the sequence of packages .
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))
Output result :
[10,20,30]
Nine .Promise.resolve and Promise.reject
Promise.resolve(2).then(res => console.log(res))
Promise.reject(3).catch(reject => console.log(reject))
Its equivalence :
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)
})
边栏推荐
- Django数据库(SQlite)基本入门使用教程
- 一本揭秘字节万台节点ClickHouse背后技术实现的白皮书来了!
- Work of safety inspection
- What management points should be paid attention to when implementing MES management system
- 普通测试年薪15w,测试开发年薪30w+,二者差距在哪?
- Difference and the difference between array and array structure and linked list
- Linear list --- circular linked list
- Code debugging core step memory
- 安德鲁斯—-多媒体编程
- Kubernetes源码分析(二)----资源Resource
猜你喜欢
Django数据库(SQlite)基本入门使用教程
Lombok makes the pit of ⽤ @data and @builder at the same time
Electrical engineering and automation
The third season of ape table school is about to launch, opening a new vision for developers under the wave of going to sea
运维管理系统有哪些特色
Huitong programming introductory course - 2A breakthrough
Redis入門完整教程:問題定比特與優化
你不可不知道的Selenium 8种元素定位方法,简单且实用
wireshark安装
AWS learning notes (I)
随机推荐
Summary of research status of inertial navigation calibration at home and abroad (abridged version)
实施MES管理系统时,哪些管理点是需要注意的
【软件测试】最全面试问题和回答,全文背熟不拿下offer算我输
代码调试core-踩内存
Have fun | latest progress of "spacecraft program" activities
MES管理系统的应用和好处有哪些
MySQL
Redis入门完整教程:复制配置
Difference and the difference between array and array structure and linked list
Es6中Promise的使用
Redis introduction complete tutorial: client case analysis
牛客编程题--必刷101之双指针篇
Google Earth engine (GEE) -- 1975 dataset of Landsat global land survey
Redis getting started complete tutorial: client management
换个姿势做运维!GOPS 2022 · 深圳站精彩内容抢先看!
What are the applications and benefits of MES management system
普通测试年薪15w,测试开发年薪30w+,二者差距在哪?
How to write test cases for test coupons?
电气工程及其自动化
Redis getting started complete tutorial: replication configuration