Reputation:
my app needs token for every api call it makes.
my problem is the functions are being executed before i make gettoken()
so my question is how to stop vue from executing code until gettoken()
is finished
My Code main.js
methods:
{
getValidToken() {
if (VueCookies.get('token') === null) {
let requestBody = {
client_id: "shopping_oauth_client",
client_secret: "shopping_oauth_secret"
};
let requestHeader = {
Authorization:
"Basic c2hvcHBpbmdfb2F1dGhfY2xpZW50OnNob3BwaW5nX29hdXRoX3NlY3JldA",
};
window.axios
.post(window.main_urls["get-token"], requestBody, {
headers: requestHeader
})
.then(response => {
VueCookies.set("aamts2124222", response.data.access_token);
return VueCookies.get("token");
});
} else {
return VueCookies.get("token");
}
}
}
cart.vue
getCartContent() {
let requestHeader = {
Authorization: "Bearer " + this.getValidToken()
};
window.axios
.get(window.main_urls["get-cart"], { headers: requestHeader })
.then(response => {
if (response.data.error === "Cart is empty") {
this.emptyCart = true;
this.loading = false;
} else {
this.loading = false;
this.cartData = response.data.data;
}
});
},
So how to wait to getValidToken()
then execute getcartcontent()
Upvotes: 0
Views: 2403
Reputation: 2899
You can use async-await
in your getCartContent()
method.
Like so:
async getCartContent() {
let token = await this.getValidToken();
let requestHeader = {
Authorization: "Bearer " + token
};
This will make sure that your requestHeader
will have token before it executes that line.
Upvotes: 1