[英]How to call a function after all async calls in loop are done?
reader.onloadend 调用异步 function addData 并且 reader.onloadend 处于循环中。
const uploadFiles = () => {
console.log(acceptedFiles)
setLoading(true)
console.log(loading)
let i = 0
let l = acceptedFiles.length
for (i = 0; i < l; i++) {
let file = acceptedFiles[i]
const reader = new window.FileReader()
reader.readAsArrayBuffer(file)
reader.onloadend = () => {
let buffer = Buffer(reader.result)
console.log(buffer)
addData(file.path, buffer)
}
}
}
这是我的异步 function addData
async function addData(name, buffer) {
const file = await myfunction()
}
在调用循环中的所有异步 addData 之后,我想调用 setLoading(false) 。 onClick function 不起作用,当我在所有异步 function 完成之前单击按钮时,加载设置为 false。
const [loading, setLoading] = useState(false)
<button onClick={() => {
uploadFiles()
setLoading(false)
}}
disabled={loading}
>
使用 Promise,您可以知道何时读取了所有文件。 基本思路如下
const uploadFiles = (evt) => { // set loading to true; const acceptedFiles = [...evt.target.files]; // Create a map of promises that will resolve when file is read const readerPromises = acceptedFiles.map(file => { return new Promise(resolve => { const reader = new window.FileReader() reader.readAsArrayBuffer(file) reader.onloadend = () => { console.log(file); let buffer = reader; // Buffer(reader.result) resolve([file.name, buffer]) } }); }); // Detects when all of the promises are fully loaded Promise.all(readerPromises).then(results => { console.log(results); // set loading to false; }); };
<input type="file" multiple onchange="uploadFiles(event)" />
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.