0

0

async await和.then:如何确保.then方法在await之后异步操作完全执行完毕?

霞舞

霞舞

发布时间:2025-03-14 09:00:06

|

1125人浏览过

|

来源于php中文网

原创

async/await.then() 的异步操作顺序控制

在使用 async/await.then() 处理异步操作时,确保 .then() 方法在 await 后的异步操作完全执行完毕后再执行,是至关重要的。本文将分析一段代码片段,并提供解决方案,以确保所有异步操作完成后再进行后续处理。

代码片段展示了父组件通过循环调用子组件的 initfilepath 方法,该方法内部使用 async/await.then() 处理图片加载。问题在于,循环会立即执行所有子组件的方法,而 await 只能保证其后单个异步操作完成,.then() 中的后续操作可能在 await 完成前就执行,导致数据不完整或错误。

子组件代码:

// 通过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) {
        const promiseList = Promise.all(this.imagepaths.map(async (path) => {
            return this.loadimgaepath(path);
        }));
        await promiseList.then(async (data) => { //这里await是多余的,then内部已经是异步的了
            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, index) => {
                        if (this.$refs[`imageref${index}`] && this.$refs[`imageref${index}`][0]) {
                            this.$refs[`imageref${index}`][0].loadimage(image);
                        }
                    });
                }
            });
        });
    }
}

loadimgaepath(path) {
    return new Promise(async (resolve, reject) => { // async 在这里也是多余的
        await request({
            url: path,
            method: 'get',
            responseType: 'arraybuffer'
        }).then((response) => {
            const imgsrc = "data:image/jpeg;base64," + btoa(new Uint8Array(response.data).reduce((data, byte) => data + String.fromCharCode(byte), ""));
            resolve(imgsrc);
        }).catch(() => {
            reject();
        });
    });
}

父组件代码片段:

// 父组件调用子组件方法
this.identifyfailed.forEach((alarm, index) => {
    this.$nextTick(() => {
        this.$refs['slideimagefaildref'][index].initfilepath(alarm.id);
    });
});

解决方案:

父组件需要使用 Promise.all 来等待所有子组件的 initfilepath 方法执行完毕。 改进后的父组件代码如下:

千图设计室AI海报
千图设计室AI海报

千图网旗下的智能海报在线设计平台

下载
const initPromises = this.identifyFailed.map(async (alarm, index) => {
    await this.$nextTick(); // 保证DOM更新
    return this.$refs['slideImageFaildRef'][index].initfilepath(alarm.id);
});

Promise.all(initPromises).then(() => {
    // 所有子组件的 initfilepath 方法执行完毕后执行的代码
    console.log('All images loaded!');
}).catch(error => {
    console.error('Error loading images:', error);
});

子组件代码优化: 子组件中的 dealimagedata 函数中的 await promiseList.then(...) 中的 await 是冗余的,因为 .then() 本身就是异步的。 loadimgaepath 函数中的 async 也是冗余的。 修改后的子组件 dealimagedata 函数如下:

async dealimagedata(data, id = 'alarmid') {
    // ... (other code) ...
    if (this.showtype !== 1) {
        Promise.all(this.imagepaths.map(async (path) => {
            return this.loadimgaepath(path);
        })).then((data) => {
            // ... (rest of the code) ...
        });
    }
}

loadimgaepath(path) {
    return new Promise((resolve, reject) => {
        request({
            url: path,
            method: 'get',
            responseType: 'arraybuffer'
        }).then((response) => {
            const imgsrc = "data:image/jpeg;base64," + btoa(new Uint8Array(response.data).reduce((data, byte) => data + String.fromCharCode(byte), ""));
            resolve(imgsrc);
        }).catch(() => {
            reject();
        });
    });
}

通过这些修改,可以确保所有异步图片加载操作完成后,再执行后续的 DOM 操作,避免数据不一致的问题。 记住要处理 Promise.allcatch 块,以便捕获任何加载错误。 此外,$nextTick 保证了在DOM更新后才调用子组件方法。

async await和.then:如何确保.then方法在await之后异步操作完全执行完毕?

相关专题

更多
DOM是什么意思
DOM是什么意思

dom的英文全称是documentobjectmodel,表示文件对象模型,是w3c组织推荐的处理可扩展置标语言的标准编程接口;dom是html文档的内存中对象表示,它提供了使用javascript与网页交互的方式。想了解更多的相关内容,可以阅读本专题下面的文章。

2712

2024.08.14

promise的用法
promise的用法

“promise” 是一种用于处理异步操作的编程概念,它可以用来表示一个异步操作的最终结果。Promise 对象有三种状态:pending(进行中)、fulfilled(已成功)和 rejected(已失败)。Promise的用法主要包括构造函数、实例方法(then、catch、finally)和状态转换。

296

2023.10.12

html文本框类型介绍
html文本框类型介绍

html文本框类型有单行文本框、密码文本框、数字文本框、日期文本框、时间文本框、文件上传文本框、多行文本框等等。详细介绍:1、单行文本框是最常见的文本框类型,用于接受单行文本输入,用户可以在文本框中输入任意文本,例如用户名、密码、电子邮件地址等;2、密码文本框用于接受密码输入,用户在输入密码时,文本框中的内容会被隐藏,以保护用户的隐私;3、数字文本框等等。

391

2023.10.12

php源码安装教程大全
php源码安装教程大全

本专题整合了php源码安装教程,阅读专题下面的文章了解更多详细内容。

65

2025.12.31

php网站源码教程大全
php网站源码教程大全

本专题整合了php网站源码相关教程,阅读专题下面的文章了解更多详细内容。

45

2025.12.31

视频文件格式
视频文件格式

本专题整合了视频文件格式相关内容,阅读专题下面的文章了解更多详细内容。

40

2025.12.31

不受国内限制的浏览器大全
不受国内限制的浏览器大全

想找真正自由、无限制的上网体验?本合集精选2025年最开放、隐私强、访问无阻的浏览器App,涵盖Tor、Brave、Via、X浏览器、Mullvad等高自由度工具。支持自定义搜索引擎、广告拦截、隐身模式及全球网站无障碍访问,部分更具备防追踪、去谷歌化、双内核切换等高级功能。无论日常浏览、隐私保护还是突破地域限制,总有一款适合你!

41

2025.12.31

出现404解决方法大全
出现404解决方法大全

本专题整合了404错误解决方法大全,阅读专题下面的文章了解更多详细内容。

232

2025.12.31

html5怎么播放视频
html5怎么播放视频

想让网页流畅播放视频?本合集详解HTML5视频播放核心方法!涵盖<video>标签基础用法、多格式兼容(MP4/WebM/OGV)、自定义播放控件、响应式适配及常见浏览器兼容问题解决方案。无需插件,纯前端实现高清视频嵌入,助你快速打造现代化网页视频体验。

9

2025.12.31

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
10分钟--Midjourney创作自己的漫画
10分钟--Midjourney创作自己的漫画

共1课时 | 0.1万人学习

Midjourney 关键词系列整合
Midjourney 关键词系列整合

共13课时 | 0.9万人学习

AI绘画教程
AI绘画教程

共2课时 | 0.2万人学习

关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号