当前位置:网站首页>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)
})边栏推荐
- Oracle中日期的使用方法实例
- Safety delivery engineer
- 安德鲁斯—-多媒体编程
- Left value, right value
- Web3's need for law
- The so-called consumer Internet only matches and connects industry information, and does not change the industry itself
- 一本揭秘字节万台节点ClickHouse背后技术实现的白皮书来了!
- Pioneer of Web3: virtual human
- CSDN 夏令营课程 项目分析
- CDB PDB 用户权限管理
猜你喜欢

2022 spring recruitment begins, and a collection of 10000 word interview questions will help you

LeetCode 77:组合

Redis introduction complete tutorial: client case analysis

Redis Getting started tutoriel complet: positionnement et optimisation des problèmes

S120驱动器基本调试步骤总结

The panel floating with the mouse in unity can adapt to the size of text content

哈希表及完整注释

慧通编程入门课程 - 2A闯关

Unity custom webgl packaging template

Redis入门完整教程:RDB持久化
随机推荐
Read fast RCNN in one article
6-6 vulnerability exploitation SSH security defense
ERROR: Could not find a version that satisfies the requirement xxxxx (from versions: none)解决办法
6-6漏洞利用-SSH安全防御
MES管理系统的应用和好处有哪些
Django数据库(SQlite)基本入门使用教程
HAVE FUN | “飞船计划”活动最新进展
MySQL
Ali yunyili: how does yunyuansheng solve the problem of reducing costs and improving efficiency?
MySQL is an optimization artifact to improve the efficiency of massive data query
What are the applications and benefits of MES management system
[node learning notes] the chokidar module realizes file monitoring
Redis getting started complete tutorial: client management
How to write test cases for test coupons?
Redis getting started complete tutorial: common exceptions on the client
Planning and design of double click hot standby layer 2 network based on ENSP firewall
Qpushbutton- "function refinement"
Cloud Mail . NET Edition
如何设计好接口测试用例?教你几个小技巧,轻松稿定
Andrews - multimedia programming