本周工作中遇见了一个问题,基于element写的一个组件,图片回显时图片无法回显。经过和领导沟通学习,原来是我对async和await的理解不够。
简单说就是在方法A中调用异步函数b,那么函数A也需要是异步的。
看以下代码
onValue: async function (value) {
if (!isEmpty(value)) {
if (this.limit === 1) {
if (isArray(this.value)) {
this.fileList = await this.convertInputValue(this.value);
} else {
this.value = this.getDownloadUrl(this.value.url);
this.fileList = [{
url: this.value.url,
thumbnail: this.getThumbnail(this.value),
}];
}
} else if (isArray(value)) {
this.fileList = await this.convertInputValue(this.value);
}
} else {
this.fileList = [];
}
},
方法:convertInputValue()是需要异步处理的,它是用来获取回显时的图片。对需要回显的图片,挨个调用接口通过循环获得图片。
/**
* 根据传入列表数据转换 url 和name
*/
async convertInputValue(list) {
for (let item of list) {
if(!item.url) {
await this.ctx.request({
url: process.env.VUE_APP_BASE_API + 'file/preview/' + item.key,
method: 'GET'
}).then(res => {
item.url = res.response.data.data
item.thumbnail = this.getThumbnail(item.url);
item.name = item[this.fieldName];
item.fileId = item[this.fieldId];
});
} else {
item.url = item[this.fieldUrl];
}
}
return list;
},
convertInputValue()方法需要等待一个接口完后再执行之后的方法,所以使用await方法。那么convertInputValue()方法也需要在前加上async。convertInputValue()在上面被调用,那么convertInputValue()被调用时,前面也需要加上async,不然会报错。个人理解的原因是,convertInputValue()被调用时,onValue不能再往下执行,需要等待。