点击保存导致接口执行顺序混乱,除了setTimeout还有什么更好的解决方案?

点击保存导致接口执行顺序混乱,除了setTimeout还有什么更好的解决方案?

避免点击“保存”按钮导致接口执行顺序错乱

点击“保存”按钮时,表单提交和图片上传同时进行,导致数据库新增接口无法获取已上传图片的URL。 本文将探讨比setTimeout更优的解决方案。

原先使用setTimeout延迟新增接口调用,但这并非最佳实践,因为延迟时间难以精确控制。 更好的方法是确保图片上传完成后再执行新增接口。以下几种方法可以实现这一目标:

1. 使用Promise:

if (this.file) {  let formData = new FormData();  formData.append('url', this.file);  uploadImg(formData, 'customer')    .then(response => {      this.fileInModel.content = response.data[0].url;      console.log(response.data[0].url, 'response22222');      // 调用新增接口      this.add(response.data[0].url);    })    .catch(error => {      // 处理上传图片错误      console.error("图片上传失败:", error);    });}

Promise确保uploadImg函数执行完毕(成功或失败)后,才会执行.then块中的代码,从而保证新增接口使用正确的图片URL。 添加.catch处理潜在的上传错误。

2. 使用回调函数:

if (this.file) {  let formData = new FormData();  formData.append('url', this.file);  uploadImg(formData, 'customer', (response) => {    this.fileInModel.content = response.data[0].url;    console.log(response.data[0].url, 'response22222');    // 调用新增接口    this.add(response.data[0].url);  }, (error) => {    // 处理上传图片错误    console.error("图片上传失败:", error);  });}

回调函数同样保证顺序执行。 此处假设uploadImg函数接受一个回调函数作为参数,并在上传成功或失败时调用该回调函数。

3. 使用async/await:

async function saveData() {  if (this.file) {    let formData = new FormData();    formData.append('url', this.file);    try {      const response = await uploadImg(formData, 'customer');      this.fileInModel.content = response.data[0].url;      console.log(response.data[0].url, 'response22222');      // 调用新增接口      await this.add(response.data[0].url);    } catch (error) {      // 处理图片上传和新增接口错误      console.error("图片上传或新增失败:", error);    }  }}

async/await 提供了更清晰易读的异步代码,try...catch块处理了潜在的错误。 await 关键字暂停执行,直到uploadImgthis.add函数完成。 saveData 函数需要声明为 async 函数。

以上方法都比setTimeout更可靠,因为它们直接依赖于图片上传的完成状态,而不是依靠不确定的时间延迟。 选择哪种方法取决于你的代码风格和项目结构。 建议优先考虑使用async/awaitPromise,因为它们更易于维护和扩展。

以上就是点击保存导致接口执行顺序混乱,除了setTimeout还有什么更好的解决方案?的详细内容,更多请关注创想鸟其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1561431.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2025年12月22日 06:29:46
下一篇 2025年12月22日 06:29:58

相关推荐

发表回复

登录后才能评论
关注微信