标签导航:

点击保存导致接口执行顺序混乱,除了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 关键字暂停执行,直到uploadImg和this.add函数完成。 saveData 函数需要声明为 async 函数。

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