【发布时间】:2018-11-20 02:04:42
【问题描述】:
我正在创建一个图片转换器,其中我的 JS 代码从用户那里获取文件输入,将其发送到我的 python 后端,在那里它们被转换并保存到一个文件夹中。然后 Python 将响应发送回 JS (react),JS 将每个文件的状态单独更新为“已转换”并重新渲染必要的组件。
我有一个为每个文件发送单独的 POST 请求的 for 循环。这很好,直到我想在转换所有文件后为整个目录创建一个 .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,但我认为我没有很好地使用它们。我不太了解这个概念,因此非常感谢您的解释。
【问题讨论】:
-
@Bravo 不,它只是设置状态。我已经阅读了多个文档,但仍然不太清楚我将如何或在何处包含一个承诺
标签: javascript reactjs asynchronous