gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 20:01:00 24 4
gpt4 key购买 nike

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com