gpt4 book ai didi

for 循环中的 node.js 回调

转载 作者:太空宇宙 更新时间:2023-11-04 02:34:04 25 4
gpt4 key购买 nike

我正在尝试读取一些数据并将其放入多数组中。要打开不同的文件,我使用 for 循环,因为我需要以正确的顺序对结果进行编号。我的问题:

我无法将数据保存在一个数组中。一旦我调用函数来读取数据,我只能在函数边界内使用结果。如何使整个数组在此函数之外可用? (很确定我搞乱了回调)。

换句话说:我正在尝试打开多个文件并将内容保存在一个数组 [[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);
});

我很感激任何建议。

尼尔斯

最佳答案

首先尝试一下这个:

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);
}
});
}

关于for 循环中的 node.js 回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24120832/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com