You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在SweetAlert2中依次显示Toast?Async/Await使用问题排查

问题排查与解决方法

问题原因

  • jQuery的$.each不兼容异步回调:$.each的设计逻辑不会等待异步函数执行完成,它会立刻遍历所有数组项,导致多个Swal.fire请求同时触发,造成SweetAlert2内部状态混乱,进而抛出TypeError: t is undefined错误。
  • 缺少自动关闭配置:原代码未设置弹窗自动关闭参数,不符合“每个Toast3秒后自动消失”的需求,弹窗会一直停留等待用户操作。

解决方法

将$.each替换为支持异步等待的for...of循环,同时给SweetAlert2添加自动关闭的配置项:

修改后的代码示例:

success: async function (data) {
    if (data.status === '110') {
        greenSwal('Done.');
    } else {
        // 用for...of替代$.each,支持异步等待
        for (const item of data.msg) {
            if (item === '2') {
                await Swal.fire({
                    icon: 'success',
                    title: 'Success',
                    timer: 3000, // 3秒后自动关闭
                    timerProgressBar: true, // 显示进度条(可选)
                    showConfirmButton: false // 隐藏确认按钮(可选)
                });
            }
            if (item === '1') {
                await Swal.fire({
                    icon: 'error',
                    title: 'Error',
                    timer: 3000,
                    timerProgressBar: true,
                    showConfirmButton: false
                });
            }
        }
    }
}

关键改动说明

  1. 外层函数声明为async:内部使用await时,外层回调函数必须标记为异步,才能正确处理Promise等待逻辑。
  2. 使用for...of遍历数组:for...of会等待每次循环中的await执行完成后,再进入下一次循环,确保弹窗依次显示、自动关闭后再弹出下一个。
  3. 添加自动关闭配置:timer:3000设置3秒自动关闭,showConfirmButton:false隐藏确认按钮,完全无需用户操作,匹配需求。

内容的提问来源于stack exchange,提问作者H. M..

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 16:09:56