Reputation: 149
Hi I would like to ask some question, I am using async await on my page to load a series of images and my problem is I am unable to pass the response from my async function.
Here's my code: In my page view I have a loop of items:
<div class="grid-x" v-for="(item, index) in cart_item_list">
<div class="cell">
<div class="grid-x grid-margin-x cart-summary">
<div class="cell large-3 small-4 shrink cart-summary-image-container">
{% comment %} <img src="https://via.placeholder.com/96x96.png" @click="processCartSummaryImage(item.product_details.images)" /> {% endcomment %}
<img :src="processCartSummaryImage(item.product_details)" />
<div style="display:none">Product ID: !! item.product_details.id !!</div>
<div style="display:none">Parent Product SKU: !! item.product_details.properties.parent_product_sku !!</div>
</div>
</div>
</div>
</div>
then I am calling this function processCartSummaryImage passing the details I needed on my async function
then on scripting I am accessing these methods
getProductImage: async function(sku) {
return await axios({
method: 'get',
url: `/api/cart/get_product_main_detail.json?filter_sku=${ sku }`
})
.then(function(response) {
//console.log('resp: ', response.data.response.image_1.url);
return response.data.response.image_1.url;
})
.catch(function (error) {
//console.log(error);
return placeholder;
});
},
processCartSummaryImage: async function(product_detail) {
var placeholder = "https://via.placeholder.com/96x96.png";
var sku = "";
var set_image = "";
// check if parent_slug_sku is available if not use the current slug
if(product_detail.properties.parent_product_sku != "") {
sku = product_detail.properties.parent_product_sku;
} else {
sku = product_detail.properties.sku;
}
try {
const resp = await this.getProductImage(sku);
console.log('response data:', resp);
return resp; // PROBLEM IS IT DOESN'T PASS ON MY IMG SRC
} catch (err) {
console.log(err);
}
},
Here's the result of the console log https://cbo.d.pr/i7h4wV
And on my img source I am getting Object Promise only https://cbo.d.pr/4ShOK3
Can you help me on this?
Upvotes: 0
Views: 1419
Reputation: 4839
You don't need to use await
and .then
. .then
is used to run something after a promise has resolved, but you're already awaiting it.
getProductImage: async function(sku) {
return await axios({
method: 'get',
url: `/api/cart/get_product_main_detail.json?filter_sku=${ sku }`
})
.then(function(response) {
//console.log('resp: ', response.data.response.image_1.url);
return response.data.response.image_1.url;
})
.catch(function (error) {
//console.log(error);
return placeholder;
});
},
Try changing the above to the below.
getProductImage: async function(sku) {
try
{
let response = await axios({
method: 'get',
url: `/api/cart/get_product_main_detail.json?filter_sku=${ sku }`
});
return response.data.response.image_1.url;
}
catch(error) {
return placeholder;
}
},
Upvotes: 1