当前位置:网站首页>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
边栏推荐
- Software designer afternoon real topic: 2009-2022
- SDL text display
- Day7:有序二叉树(二叉搜索树)
- Mutual conversion of camera internal parameter matrix K and FOV
- 基于海思3559 高效率的 0延时 0拷贝 qt播放器方案
- Why learn service grid istio
- C # add multi line and multi column text watermark in word
- [hdlbits questions] Verilog language (3) modules: hierarchy section
- Split very long line of words into separate lines of max length
- Website construction of information exchange platform for China Africa South South cooperation based on PHP
猜你喜欢

Nezha d1-h test microbench

滑雪手机端H5小游戏源码下载

一元函数积分学_分部积分法

Day7:有序二叉树(二叉搜索树)

Binary tree visualization

由一个蓝桥杯基础题报时助手而引出的常见误区

基于PHP的中非南南合作信息交流平台网站建设

TFIDF examples and explanations

How to be a self disciplined person?

Is there a "fingerprint" in the structure of AAAI 2022 | Gan? Generating network structure from forged image traceability
随机推荐
Mutual conversion of camera internal parameter matrix K and FOV
TypeError: ‘str‘ object is not callable的错误原因
The finished product of wechat campus maintenance and repair applet graduation design (1) development outline
[CSAPP Practice Problem 2.32] tsub_ OK (int x, int y) judge whether complement subtraction overflows
Solve the problem that the win10 account has no administrator rights
TFIDF examples and explanations
Univariate function integration_ Partial integral method
基于PHP的中非南南合作信息交流平台网站建设
C# 合并集合
sentinel简单限流和降级demo问题记录
C语言学习日记3——realloc函数
[wp]ctfshow-web getting started - Explosion
Sccm2012r2 network deployment reinstallation system
PyTorch 模型 onnx 文件的导出和调用
[artifact] screenshot + mapping tool snipaste
Scala foundation [set 01]
Analysis of CMS station building system of common PHP in China
[server data recovery] a data recovery case of a brand ProLiant server raid paralysis, database file loss, and database file backup damage
Wechat campus maintenance and repair applet graduation design finished product of applet completion work (4) opening report
Error when creating dataset with mindscore