我的组件中有一个函数,用于将文件处理到数组中,然后通过调用其函数之一将数组上传到数据服务。
我正在将上传的 CSV 文件解析为 JSON 数据数组。在 processFiles
函数中,我循环遍历数组以将数据推送到 processedData
数组中。之后,我从数据服务中调用 this.passData.pushPassedData
函数来推送处理后的数据。
问题是 this.passData.pushPassedData
函数在 for 循环完成处理文件之前执行,并且仅推送到数据服务一个空数组。
files = []; // array to store uploaded files
processedData = []; // array to store processed JSON data
processFiles() {
for (let file of this.files) {
this.papaService.parse(file, {
header: true,
dynamicTyping: true,
complete: (results) => {
console.log("Detected: ", results.data);
for (let entry of results.data) {
if (entry.Interface !== "") {
let _entry: RuleFormat;
_entry = {
abc: "xyz",
def: "123",
}
this.processedData.push(_entry);
console.log("Pushed: " + JSON.stringify(_entry));
}
}
}
})
}
console.log("Pushed: " + JSON.stringify(this.processedData));
this.passData.pushPassedData(this.processedData);
}
从控制台可以看到,只有调用数据服务函数后,数据才会被压入数组。
有没有办法让函数调用等待for循环?
最佳答案
您可以在 processFiles
中添加一个计数器,并在 complete
回调中递增它。当所有文件都处理完毕后,您将调用 this.passData.pushPassedData
:
files = []; // array to store uploaded files
processFiles() {
let processedFileCount = 0;
for (let file of this.files) {
this.papaService.parse(file, {
...
complete: (results) => {
processedFileCount += 1;
for (let entry of results.data) {
...
}
if (processedFileCount >= files.length) {
// All files have been processed
this.passData.pushPassedData(this.processedData);
}
}
});
}
}
关于angular - 延迟服务调用直到循环结束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48055297/