使用swal完成AJAX请求后如何等待弹窗关闭再执行页面刷新
问题原因
你在第二个then回调中调用的提示类swal本身会返回一个Promise对象,该Promise只会在弹窗完全关闭后才进入resolve状态。你之前的写法没有将这个Promise返回给链式调用,导致后续逻辑不会等待弹窗关闭就提前执行。
解决方法
在第二个then里把swal调用的返回值return出去,再追加一个then回调写页面刷新逻辑即可。如果只需要成功场景下刷新页面,可以单独加判断控制。
修改后的完整代码
$('#config-reset').click(function(event) { event.preventDefault() swal({ text: 'some text', dangerMode: true, showLoaderOnConfirm: true, buttons: true, }) .then((result) => { if (result !== null) { return $.post("url") } // 取消操作时抛出错误中断后续链式调用,避免执行刷新 throw new Error('user_cancel') }) .then((result) => { if (result.result.success == 'done') { // 返回成功提示弹窗的Promise,链式调用会等待弹窗关闭 return swal({ text: "Done", icon: "success", }).then(() => 'need_refresh') } else { return swal(result.result.error) } }) .then((flag) => { // 只有成功场景下的弹窗关闭后才执行刷新 if (flag === 'need_refresh') { location.reload() } }) .catch(err => { // 排除用户主动取消的情况,只报错接口错误 if (err.message !== 'user_cancel') { swal(err.statusText); } }); })
内容的提问来源于stack exchange,提问作者Larry Martell
相关产品推荐
相关产品推荐

