async和await关于图片回显

本周工作中遇见了一个问题,基于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不能再往下执行,需要等待。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值