async await 以及.then 希望.then中的方法也一并执行到底,不要在执行完毕await之后就跳出来,最后再执行.then中的方法。
// 父组件调用子组件方法
this.identifyFailed.forEach((alarm: Alarm, index: number) => {
this.$nextTick(()=>{
this.$refs['slideImageFaildRef'][index].initFilePath(alarm.id)
})
})
// 子组件实现如下所示
// 通过id获取告警图片
async initFilePath(alarmId) {
this.isShowMoreWaterfallImage = false;
const { code, data } = await getImagePathOfAlarmAsync(alarmId)
if (code == 200) {
this.dealImageData(data)
} else {
this.showType = 1
}
}
async dealImageData(data, id = 'alarmId') {
this.imgList = []
this.carouselCurrentIndex = 0
this.imagePaths = data
this.imageFormPathId = id
this.showType = this.imagePaths.length == 0 ? 1 : (this.imagePaths.length == 1 ? 2 : 3)
if (this.showType !== 1) {
let promiseList = Promise.all(this.imagePaths.map(async(path) => {
return this.loadImgaePath(path)
}))
await promiseList.then(async (data: any)=>{
this.imgList = data
this.$nextTick(()=>{
if (this.showType === 2) {
if (!!this.$refs.imageRef)
this.$refs.imageRef.loadImage(data[0])
} else if (this.showType === 3 ) {
data.forEach((image: any, index: number) => {
if (!!this.$refs[`imageRef${index}`][0])
this.$refs[`imageRef${index}`][0].loadImage(image)
})
}
})
})
}
}
loadImgaePath(path) {
return new Promise(async(resolve, reject) => {
await request({
url: path,
method: 'get',
responseType: 'arraybuffer'
}).then((response: any) => {
let imgSrc = "data:image/jpeg;base64," + btoa(new Uint8Array(response.data).reduce((data, byte) => data + String.fromCharCode(byte), ""))
resolve(imgSrc)
}).catch(()=>{
reject()
})
})
}
在dealImageData方法中,得到promiseList,希望promiseList.then里面的方法执行完毕后,父组件再去调用新一次的循环
父组件用 forEach 调用子组件的异步方法,会同时运行,并且不会等待。你需要用 map 返回一个promise的列表,然后再等待异步完成。