嗨,我想问一个问题, 我在页面上使用async等待来加载一系列图像,但问题是我无法传递异步函数的响应。
这是我的代码: 在页面视图中,我有一个项目循环:
<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>
然后我将此函数称为 processCartSummaryImage ,以传递我在异步函数中所需的详细信息
然后在编写脚本时,我正在访问这些方法
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);
}
},
这是控制台日志的结果 https://cbo.d.pr/i7h4wV
在我的img源上,我仅获得对象承诺 https://cbo.d.pr/4ShOK3
您能帮我吗?
答案 0 :(得分:1)
您不需要使用await
和.then
。 .then
用于在诺言解决后运行某些事情,但是您已经在等待它。
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;
});
},
尝试将以上内容更改为以下内容。
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;
}
},