标签导航:

点击保存时上传和新增接口的调用顺序如何优化?

优化点击保存时上传和新增接口的调用顺序

用户点击保存按钮时,系统需要依次调用上传和新增接口。由于上传接口的返回结果需要时间,直接调用新增接口会导致数据缺失。 为了避免使用setTimeout这种不优雅的延迟方案,最佳实践是在上传接口的成功回调函数中直接调用新增接口,并将上传结果作为参数传递。

这种异步操作的处理方式,确保新增接口在获得上传接口的返回值后才执行,避免了数据不一致的问题。

改进后的代码示例:

if (this.file) {
  const formData = new FormData();
  formData.append('url', this.file);

  uploadImg(formData, 'customer')
    .then(response => {
      //  校验上传结果,确保成功后再调用新增接口
      if (response.status === 200 && response.data && response.data[0] && response.data[0].url) {
        this.fileInModel.content = response.data[0].url;
        this.add(response.data[0].url); // 将上传结果作为参数传递给新增接口
      } else {
        // 处理上传失败的情况,例如显示错误信息
        console.error('图片上传失败:', response);
        // 可选:在此处显示错误提示给用户
      }
    })
    .catch(error => {
      // 处理上传过程中发生的错误
      console.error('图片上传错误:', error);
      // 可选:在此处显示错误提示给用户
    });
}

此方案利用Promise的.then()方法处理异步操作,清晰地表达了依赖关系,避免了setTimeout带来的不确定性以及潜在的性能问题。 此外,添加了错误处理机制,提升了代码的健壮性。