当前位置:网站首页>The use of new promise, async and await in the project, and the practical application of promise.all in the project
The use of new promise, async and await in the project, and the practical application of promise.all in the project
2022-07-25 19:45:00 【Mr. Liu works hard】
Let's get to know async and await as well as promiss
What is? async/await
async/await It's a new way to write asynchronous code , It is generator The grammar sugar of , Previous methods include callback functions and Promise.
async/await Is based on Promise Realized , It can't be used for normal callback functions .
async/await And Promise equally , It's non blocking .
async/await Make asynchronous code look like synchronous code , That's the magic of it .
What is? Promise
Promise Is a solution to asynchronous programming , More than traditional solutions —— Callback functions and events —— More reasonable and more powerful .
So-called promise, It's simply a container , It holds an event that will end in the future ( This is usually an asynchronous operation ) Result . grammatically ,Promise It's an object , From it you can get messages for asynchronous operations .
difference
- There is one more in front of the function async keyword .await Keywords can only be used for async Within the function defined .async The function returns one implicitly Promise, The promise Of resolve The value is return Value .
- await Must be used in asynchronous functions ; among await Limited ( Not allowed in arrow function ; Not allowed in synchronous function declaration ; Not allowed in synchronous function expression ; If you use await Will throw SyntaxError.)
use async/await Better
- Use async Functions can make code much simpler , No need to think Promise Just as much then, There is no need to write anonymous functions to handle Promise Of resolve Value , There's no need to define redundant data Variable , It also avoids nested code .
- async/await Give Way try/catch Can handle synchronous and asynchronous errors at the same time . In the following example ,try/catch Can't handle JSON.parse Error of , Because it is in Promise in , We need to use .catch, Such errors will make the code very redundant .
Example :
async function update(data) {
await this.changeListChOrgInfo();// When changeListChOrgInfo() After the execution is complete , Just execute the following this.iscompany The operation of
this.iscompany = true;
},
function changeListChOrgInfo({commit}) {// Return to one Promise object
return new Promise((resolve, reject) => {
changelistChOrgInfo({})// One ajax request
.then(response => {
if(!response.body){
}
else{
}
resolve()
})
.catch(error => {
console.log(error);
reject();
});
})
}
Assume requirements in the project : In the development and application of actual projects, we need to implement the first two methods , Use the data returned by the two methods as parameters to execute the third method
And that's where we need to use it new promise、resolve、promise.all Other methods .
In the actual , It can be adapted according to the actual situation of the project
Method 1 : Suppose we want to get account information , It must be a way , Written in methods in
// Account information acquisition
getAccount(){
return new Promise((resolve,reject)=>{
this.$axios.post(CONFIG.httphost() + '/user/queryUser',{
st:1,
limit:0
}).then(resp =>{
let res = resp.data; // Return the data
let code = res.code; // data code code , It's usually 200
if(!code){
this.accountList = res.data;
// It's worth noting that here ,new promise The correct way to request is to resolve come out , To continue down
resolve();
}else{ Failure words , What to return or prompt , Read and write }
})
})
},
Method 2 :
// Get unit
getDW() {
return new Promise((resolve,reject)=>{
this.$axios.post(CONFIG.httphost() + "/MessageShowController/showDwMessage", {
st: 1,
limit: 0
}).then((resp) => {
let res = resp.data;
let code = res.code;
if (!code) {
this.dwList = res.data;
resolve()
} else {
this.giveMsg(" Request data failed ");
}
});
})
},
Method 3 : Get the first, the second, and then get the third
// get data
getData() {
Promise.all([
this.getAccount(), // first
this.getDW(), // the second
]).then(res=>{ // The request succeeded in obtaining the third interface
// The request method here is flexible according to the actual packaging
this.$axios.post(CONFIG.httphost() + "/MessageCollectorController/showBmJurisdiction", {
dw_id: self.dw_id, // Parameters received
userid:this.userid, // Parameters received
})
.then((resp) => { // assignment
let res = resp.data;
let code = res.code;
if (!code) {
this.$nextTick(() => {
this.getRoleMenu(res.data);
});
}else{ Write but not write , See the demand .}
})
.catch((err) => {
});
})
}
We have the opportunity to communicate , Welcome to correct . Thank you
边栏推荐
- Kcon 2022 highlights and agenda revealed!
- Website construction of information exchange platform for China Africa South South cooperation based on PHP
- Basic practice of Blue Bridge Cup - shape retrieval of matrix (C language)
- 微信小程序开发之全局配置与页面配置
- Yyds dry inventory how to locate browser page crash
- Mutual conversion of camera internal parameter matrix K and FOV
- 二叉树可视化
- what is qml in qt
- Security Basics 4 - regular expressions
- Creative drop-down multi choice JS plug-in download
猜你喜欢

Wechat campus maintenance and repair applet graduation design finished product (7) Interim inspection report

Research and application of servo driver in robot

高效生成接口文档好方法

随机梯度下降法、牛顿法、冲量法、AdaGrad、RMSprop以及Adam优化过程和理解

Legal mix of collations for operation 'Union' (bug record)

UNET and mask RCNN

Flutter 小技巧之优化你使用的 BuildContext

创意下拉多选js插件下载
![[wp]ctfshow-web入门-爆破](/img/4b/6d8f4c044578382b9353d4d1c69c8f.png)
[wp]ctfshow-web入门-爆破

Sccm2012r2 network deployment reinstallation system
随机推荐
The finished product of wechat campus maintenance and repair applet graduation design (1) development outline
高效生成接口文档好方法
Mobile phone touch picture slider rotation plug-in photoswipe.js
A high efficiency 0-delay 0-copy QT player scheme based on Hisilicon 3559
C# 合并集合
二叉树可视化
滑雪手机端H5小游戏源码下载
创意下拉多选js插件下载
什么是唯心主义
919. 完全二叉树插入器
Network data request for wechat applet development
Js分页插件支持表格、列表、文本、图像
Mutual conversion of camera internal parameter matrix K and FOV
加州大学|用于未指定环境的可行对抗鲁棒强化学习
Authorized wireless communication standard
Selenium 设置元素等待的三种方式详解
Bash does not add single quotes to your string
由一个蓝桥杯基础题报时助手而引出的常见误区
High number_ Chapter 3 learning experience and summary of multiple integral
GBASE 8s UDR内存管理_01_mi_alloc