延迟服务调用直到循环之后
Delay service call until after loops
我的组件中有一个函数,它是将文件处理成一个数组,然后通过调用其中一个函数将数组上传到数据服务。
我正在将上传的 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);
}
}
});
}
}
我的组件中有一个函数,它是将文件处理成一个数组,然后通过调用其中一个函数将数组上传到数据服务。
我正在将上传的 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);
}
}
});
}
}