我无法将数据保存在一个数组中。一旦我调用函数来读取数据,我只能在函数边界内使用结果。如何在此功能之外使整个阵列可用? (很确定我搞砸了回调)。
换句话说:我正在尝试打开多个文件并将内容保存在一个数组[[file1],[file2],...]中。
这是我的代码:
var einlesen = require ('./einlesen/einlesen.js');
var einzeln = function(arg, callback){ //this is the function I use to read the data (it works fine, I checked it separately)
einlesen.einlesen(arg[0], arg[1], arg[2], function(err, output){ //this function opens a file, works on the content and returns an array containing the needed data
if (err) { return cb1(err); }
callback(output);
});
}
var daten_einlesen = function (callback){
var tabellenarray = []; //initiating the array in which the whole info should go
var tabelleninfos = [ //this array contains the info which data should be read, you only need to know that there are 16 files to be read, the rest is not important
['gvz', '<|>', '1,1,1,0,1,0,0,0,1'],
['GZV', ';', '1,1,1,1,1,1,1,1'],
['XPG', ';', '1,1,1,1,1'],
['ABF', ';', '1,1,1,1,1,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1'],
['GUS', '<|>', '1,1,0,1,0,0,0,0,1,1,1'],
['XPA', '<|>', '1,1,1'],
['ALW', '<|>', '1,1,1'],
['TAL', '<|>', '1,1,1'],
['ALB', '<|>', '1,1,0,1,1,1,1,1,1'],
['ZLB', '<|>', '1,1,1'],
['XAW', '<|>', '1,1,1'],
['SWS', ';', '1,1,1,1,1,1,1,1,1,1'],
['PRO', '<|>', '1,1'],
['VBP', '<|>', '1,0,1'],
['ZVP', '<|>', '1,1,1'],
['config', ';', '0,0,1']];
for (var i = 0; i < 3; i++){ //this is the loop where i try to open the files one by one and input them into the "tabellenarray"
einzeln(tabelleninfos[i], function(tabelle){
tabellenarray[i] = tabelle; //data is saved to the array but I lose the info onto the next step of the loop, if i put the final callback (below) in here the loop doesnt work anymore (naturally)
});
}
callback(tabellenarray);
}
daten_einlesen(function(piep){ //calling the whole function
console.log(piep);
});
我很感激任何建议。
尼尔斯
答案 0 :(得分:0)
首先尝试这个:
var pending = 3,complete=0;
for (var i = 0; i < pending; i++){ //this is the loop where i try to open the files one by one and input them into the "tabellenarray"
einzeln(tabelleninfos[i], function(tabelle){
tabellenarray[i] = tabelle; //data is saved to the array but I lose the info onto the next step of the loop, if i put the final callback (below) in here the loop doesnt work anymore (naturally)
if(++complete >= pending){
callback(tabellenarray);
}
});
}