这是代码:
var getFile = document.getElementById("roll");
var init = getFile.files;
var rawResults = [];
if(init.length > 1){
for(var i = 0, ii = init.length; i < ii; i++){
Papa.parse(init[i], {
delimiter: "", // auto-detect
newline: "", // auto-detect
header: true,
dynamicTyping: false,
preview: 0,
encoding: "",
worker: false,
comments: false,
step: undefined,
complete: function(results, file) {
rawResults.push(results.data);
},
error: undefined,
download: false,
skipEmptyLines: false,
chunk: undefined,
fastMode: undefined,
beforeFirstChunk: undefined,
withCredentials: undefined
});
}
var flattening = _.flatten(rawResults);
console.log(rawResults);
console.log(rawResults.length);
}
当我尝试在
_.flatten
数组上运行rawResults
下划线功能时,它变成空的,因为getFile
函数本质上是异步的,因此该数组尚未准备好数据。该脚本采用一个上传的文件,然后通过Papa Parse解析,然后将结果最终填充到
rawResults
数组中。我试图创建一个像这样的回调函数:
function firstfunction(callbackfxn){
// Put the asynchronous getFile code here.
callbackfxn();
};
function secondfunction(){
firstfunction(function(){
// Put the parsing code in here
});
};
我尝试了其他回调变体,但没有按预期运行它的运气。
最佳答案
为什么不使用某些控制流库,例如bluebird或async.js?
这是使用async#each的示例
async.js
async.each(init, function(file, callback) {
Papa.parse(init[i], {
delimiter: "", // auto-detect
newline: "", // auto-detect
header: true,
dynamicTyping: false,
preview: 0,
encoding: "",
worker: false,
comments: false,
step: undefined,
complete: function(results, file) {
rawResults.push(results.data);
callback();
},
error: undefined,
download: false,
skipEmptyLines: false,
chunk: undefined,
fastMode: undefined,
beforeFirstChunk: undefined,
withCredentials: undefined
});
}, function(error) {
// do something if error
var flattening = _.flatten(rawResults);
console.log(rawResults);
console.log(rawResults.length);
});
循环遍历数组的每个元素,将迭代器函数应用于该元素。一旦触发complete事件,它将调用回调函数以告知该函数它已完成。
async#each
的最后一个参数是错误函数。处理完所有元素后,将调用它。调用此函数后,应填充rawResults。