带有for循环POST请求的javascript/react-async/await



我正在创建一个图片转换器,我的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 });
};

最新更新