当前位置:网站首页>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)
})
边栏推荐
- PCL 常用拟合模型及使用方法
- Detailed explanation of 19 dimensional integrated navigation module sinsgps in psins (initial assignment part)
- Metaforce force meta universe fossage 2.0 smart contract system development (source code deployment)
- Cglib agent in agent mode
- Electrical engineering and automation
- 一文读懂Faster RCNN
- MATLB|具有储能的经济调度及机会约束和鲁棒优化
- 数论 --- 快速幂、快速幂求逆元
- Rethinking of investment
- Django database (SQLite) basic introductory tutorial
猜你喜欢
普通测试年薪15w,测试开发年薪30w+,二者差距在哪?
Pioneer of Web3: virtual human
Niuke programming problem -- double pointer of 101 must be brushed
Redis入门完整教程:问题定位与优化
A complete tutorial for getting started with redis: problem location and optimization
Redis入門完整教程:問題定比特與優化
Redis入门完整教程:复制配置
Leetcode 77: combination
wireshark安装
基于ensp防火墙双击热备二层网络规划与设计
随机推荐
Dotconnect for DB2 Data Provider
写作系列之contribution
QT常见概念-1
Niuke programming problem -- double pointer of 101 must be brushed
QT common Concepts-1
Redis入門完整教程:問題定比特與優化
你不可不知道的Selenium 8种元素定位方法,简单且实用
牛客编程题--必刷101之双指针篇
MetaForce原力元宇宙佛萨奇2.0智能合约系统开发(源码部署)
进程管理基础
Redis introduction complete tutorial: client case analysis
uniapp的表单验证
Web3's need for law
MySQL
HAVE FUN | “飞船计划”活动最新进展
Safety delivery engineer
Leetcode 77: combination
How to write test cases for test coupons?
A complete tutorial for getting started with redis: RDB persistence
[socket] ① overview of socket technology