Usage scenario: Function A requests dataA from the background, and function B needs to use dataA to perform some calculations immediately or request other data from the background
this.A();
this.B();
Copy the code
Error: data from A is not returned when B is executed because of asynchracy.
Method 1
Function A is executed first:
A() {
const params = {
projectName: this.listSearchKey
};
/ / use of promise
return new Promise((resolve, reject) = > {
// Asynchronous request
projectList(params)
.then(res= > {
if (res.code === '0') {
this.dataA = res.data;
// Return the desired data
resolve(this.dataA);
}
})
.catch(err= > {
console.error(err);
});
});
}
Copy the code
And then we execute function B
B(id) {
// Use dataA from function A, and want to execute as soon as it gets the return data
const params = {
projectId: id || this.dataA[0].projectId
};
taskList(params)
.then(res= > {
if (res.code === '0') {
this.tableData = res.data.list;
this.total = res.data.total;
}
})
.catch(err= > {
console.error(err);
});
},
Copy the code
Write this at execution time
A().then(val= > {
B();
});
Copy the code
Method 2
async function asyncMain(){
try{
let result =await A();
result = await B();
}catch(err){
console.error(err);
}
}
asyncMain()
Copy the code
Complete asynchronous to synchronous implementation
For a true asynchronous to synchronous implementation, you can choose to use Promise or its All /race, async/await. If a purely interdependent interface has only two interfaces, you only need to follow the preceding steps.
But if there are multiple interfaces that depend on each other, you might want to use promise.all/race or async/await.
Resolve is a promise object that will allow the program to continue execution. Promise. Reject allows promise. All /race or async/await to catch errors better.
Then, the following steps are needed to complete such work:
Step 1: Make each asynchronous function return a Promise object and conditionally return resolve or reject;
1 / / interface
handleData() {
return new Promise((resolve, reject) = > {
taskDetail()
.then(res= > {
If code is not 0, reject is required
if(res.code ! = ='0') {
reject(res.msg);
return;
}
// If the status is normal, resolve is required
this.ftpInfoOptions = res.data;
resolve();
})
.catch(err= > {
// A catch is also a reject
return reject(err);
});
});
},
Copy the code
2 / / interface
getSystemOptions() {
const params = {
apsRole: 0.taskType: this.taskType
};
return new Promise((resolve, reject) = > {
getApSystemByApsRoleAndTaskType(params)
.then(res= > {
if(res.code ! = ='0') {
reject(res.msg);
return;
}
this.systemOptions = res.data;
resolve(res.data);
})
.catch(err= > {
return reject(err);
});
});
},
Copy the code
The second step is to confirm the dependencies between multiple asynchronous functions and select methods.
The two interfaces mentioned above are the detail interface and the receiving interface. Of course, the detail interface depends on multiple interfaces, so only one interface is used here.
In the business process of the company, when editing a message, many interfaces must be obtained before the details, so that the data can be displayed easily. We choose to use async/await. In addition to interdependence and sequencing, we also consider that if the front interface is abnormal, there is no need to call the rest interfaces.
Creating a new message takes into account that one interface should not block subsequent interfaces, so promise.all is selected.
// Created
async created() {
// Check whether it is in edit state
const isEdit = this.taskId ! = =`null`;
try {
// These two interfaces must be called first regardless of whether they are created
await this.getSystemOptions();
await this.getReceiverOptions();
// Details interface, edit only call
isEdit && (await this.handleData());
} catch (error) {
// Accept the interface
console.error(error);
}
// Select all if data from multiple asynchronous interfaces must be retrieved in random order before an asynchronous operation can be performed
Promise.all([
!isEdit ? this.getFtpInfo('add') : ' ',
!isEdit ? this.getCstoreInfo({}) : ' ',
])
.then(() = > {
// Do the following
})
.catch(error= > {
// If two interfaces report an error, only one catch is allowed
console.error(error);
});
},
Copy the code