javascript/react - 异步/等待 for 循环 POST 请求

标签 javascript reactjs asynchronous

我正在创建一个图片转换器,我的 JS 代码从用户那里获取文件输入,将其发送到我的 python 后端,在那里它们被转换并保存到一个文件夹中。 Python 然后将响应发送回 JS (react),JS 将每个文件的状态分别更新为“已转换”并重新呈现必要的组件。

我有一个 for 循环,它为每个文件发送单独的 POST 请求。这很好,直到我想在转换所有文件后为整个目录创建一个 .zip。我的问题就在那里。我的 zip 总是返回空文件或文件不完整。

// function which takes the file inputs from user
uploadBatch = async () => {
  const files = this.getFilesFromInput();
  const batch = Math.floor(Math.random() * 999999 + 100000);
  for (let i = 0; i < files.length; i++) {
    // sets the state which will then be updated
    await this.setState(
      {
        files: [
          ...this.state.files,
          {
            // file state values
          }
        ]
      },
      () => {
        const formData = new FormData();
        // appends stuff to form data to send to python
        axios
          .post('/api/upload', formData, {
            headers: {
              'Content-Type': 'multipart/form-data'
            },
            responsetype: 'json'
          })
          .then(response => {
            // update the state for this particular file
          });
      }
    );
  }
  return batch;
};

// function which zips the folder after files are converted
handleUpload = async e => {
  e.preventDefault();
  // shouldn't this next line wait for uploadBatch() to finish before 
  // proceeding?
  const batch = await this.uploadBatch();
  // this successfully zips my files, but it seems to run too soon
  axios.post('/api/zip', { batch: batch }).then(response => {
    console.log(response.data);
  });
};

我用过 async/await,但我认为我用得不好。我不太从根本上理解这个概念,所以非常感谢解释。

最佳答案

无论何时调用 setState(),组件都会重新渲染。理想情况下,您应该完成所有操作并在最后调用 setState()

像这样的事情应该让事情为你工作

// function which takes the file inputs from user
uploadBatch = async () => {
  const files = this.getFilesFromInput();
  const batch = Math.floor(Math.random() * 999999 + 100000);
  const files = [];
  for (let i = 0; i < files.length; i++) {
    const formData = new FormData();
    // appends stuff to form data to send to python
    const res = 
      await axios
        .post('/api/upload', formData, {
          headers: {
            'Content-Type': 'multipart/form-data'
          },
          responsetype: 'json'
        });

    files.push('push data into files arr');
  }

  return { files, batch };
};

// function which zips the folder after files are converted
handleUpload = async e => {
  e.preventDefault();
  // get batch and files to be uploaded and updated
  const { files, batch } = await this.uploadBatch();
  // this successfully zips my files, but it seems to run too soon
  await axios.post('/api/zip', { batch: batch }).then(response => {
    console.log(response.data);
  });

  // set the state after all actions are done
  this.setState( { files: files });
};

关于javascript/react - 异步/等待 for 循环 POST 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53385197/

相关文章:

javascript - 如何根据列条件设置默认颜色

javascript - 无法使用 QUnit Test 中声明的变量

javascript onclick 和方法

css - 有没有一种方法可以将下拉元素显示在另一个元素上以收集元素

java.awt.EventQueue.invokeLater 解释

Javascript 不会更新 session ,只有页面重新加载才能完成这项工作

reactjs - React.ComponentProps 的 React 语法问题

javascript - This.props.dispatch 不是一个函数 - React-Redux

javascript - 当多个 API 调用时只运行一次响应拦截器

javascript - 无法获取函数的值