async await执行结束后,希望.then中的方法也一并执行完毕,再跳出方法,要如何操作?

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里面的方法执行完毕后,父组件再去调用新一次的循环

阅读 720
avatarAI BotBETA

要确保.then中的方法执行完毕后再跳出当前方法,并且父组件在新一轮的循环中等待所有子组件的.then方法完成,你可以使用Promise.all来管理这些异步操作。下面是一个修改后的示例,展示了如何实现这个需求:

首先,在子组件的initFilePath方法中,返回一个Promise,这样父组件可以等待这个Promise完成:

// 子组件
initFilePath(alarmId) {
    return new Promise((resolve, reject) => {
        this.isShowMoreWaterfallImage = false;
        getImagePathOfAlarmAsync(alarmId)
            .then(({ code, data }) => {
                if (code == 200) {
                    this.dealImageData(data)
                        .then(() => resolve()) // 当dealImageData完成后,解决这个Promise
                } else {
                    this.showType = 1;
                    reject(); // 如果出错,拒绝这个Promise
                }
            })
            .catch(reject); // 如果getImagePathOfAlarmAsync出错,拒绝这个Promise
    });
}

// 其他方法保持不变...

然后,在父组件中,你可以使用Promise.all来等待所有子组件的initFilePath方法完成:

// 父组件
this.identifyFailed.forEach((alarm, index) => {
    // 保存每个Promise,以便稍后使用Promise.all
    const initPromises = [];

    this.$nextTick(() => {
        this.$refs['slideImageFaildRef'][index].initFilePath(alarm.id)
            .then(() => {
                // 在每个initFilePath完成后,将Promise添加到数组中
                initPromises.push(Promise.resolve());
            })
            .catch((error) => {
                console.error(`Error initializing image for alarm ${alarm.id}:`, error);
                // 如果需要,可以在这里处理错误,或者跳过出错的项
            });
    });
});

// 等待所有initFilePath完成
Promise.all(initPromises)
    .then(() => {
        // 当所有initFilePath都完成后,执行新一轮的循环或其他操作
        console.log('All images initialized, proceed with next step...');
        // 这里可以调用新的循环或执行其他需要的逻辑
    })
    .catch((errors) => {
        // 如果其中有任何错误,这里会捕获到
        console.error('Errors occurred while initializing images:', errors);
    });

注意,Promise.all会等待所有传入的Promise都完成(或者其中一个被拒绝)才会解析或拒绝。因此,当所有子组件的initFilePath方法都完成后,Promise.all(initPromises)会解析,然后你可以执行接下来的逻辑。

确保在initFilePath方法中正确处理任何可能的错误,并在父组件中捕获并处理这些错误,以避免程序意外中断或产生不可预测的行为。

1 个回答

父组件用 forEach 调用子组件的异步方法,会同时运行,并且不会等待。你需要用 map 返回一个promise的列表,然后再等待异步完成。

const initPromises = this.identifyFailed.map(async (alarm: Alarm, index: number) => {
    await this.$nextTick()
    returen await this.$refs['slideImageFaildRef'][index].initFilePath(alarm.id)
})

Promise.all(initPromises).then(....)
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题