I have two api calls I am making in a Vue method. I need to be able to set the api results into two variables and then call them in another method for manipulation. How can this be done without using "Promise.all"
currently I have this but the variables log "undefined"
apiCall () {
this.Loading = true;
const resultOne = get('lots/path1', { locationId: '9047695746459876', fromDate: moment(this.dateRange[0]).format('YYYY-MM-DD'), toDate: moment(this.dateRange[1]).format('YYYY-MM-DD') }).then((result) => {
console.log(result, 'result 2')
});
const resultTwo = get('lots/path2', { locationId: '897349823749237', fromDate: moment(this.dateRange[0]).format('YYYY-MM-DD'), toDate: moment(this.dateRange[1]).format('YYYY-MM-DD') }).then((result) => {
console.log(result, 'result 2')
});
console.log(resultOne, resultTwo) //returning undefined
this.Loading = false;
},
CodePudding user response:
By using async/await.
Edit: In this case they will be called in a sequence, the second one will be made after the first one is resolved (this is useful only in cases when you need data from the first req to make the second req).
If you want to make them in the same time you will have to use Promise.all()
or Promise.allSettled()
.
Example:
async apiCall() {
this.Loading = true;
try {
const resultOne = await get('lots/path1', { ... });
console.log(resultOne);
const resultTwo = await get('lots/path2', { ... });
console.log(resultTwo);
} catch (err) {
console.error(err);
} finally {
this.Loading = false;
}
}