[英]why is not working properly async.each nodejs?
我正在尝试使用async.each函数从两个查询中获取带有我的结果的数组。 之后,我需要将此结果呈现在网页中。
async.each函数正确计算了变量结果,但是,我无法将此变量导出到函数外部并进行渲染,而且我不明白为什么。
在这里,我附加了代码,并在其中进行了测试。 我意识到,当我调用“ callback1”时,该函数(错误)不起作用,并且在控制台中没有得到变量列表(因此以后将无法渲染它)。 如果有人可以帮助我,我将不胜感激。 非常感谢。
var list = [];
async.each(data,
function(elem, callback1){
var classgene = '';
var custom_gene = {};
custom_gene = {Name_Gene: elem['Name_Gene']};
if (elem['Type_Gene'] == "reference") {
async.waterfall([
function(callback2){
var id = elem['Id_Genes'];
geneModel.getGenesRefClass(id, function(error, data2){
classgene = data2[0]['Class_Name'];
custom_gene['classgene'] = classgene;
callback2(custom_gene);
});
},
], function(custom_gene, err){
list.push(custom_gene);
console.log(list);
callback1();
});
}
}, function(err){
// if any of the saves produced an error, err would equal that error
if(err){
console.log(list);
}else{
console.log(list);
}
});
您的代码有一些问题:
callback2(null, custom_gene)
(第一个参数是为错误保留的;如果没有,则为null
)。 最好,还应该检查是否由geneModel.getGenesRefClass()
返回error
; function(custom_gene, err)
的参数(它应该变成function(err, custom_gene)
); elem['Type_Gene']
不等于“ reference”时 ,您仍然应该调用callback1()
,否则async.each()
不知道代码已经完成; 因此,代码将变成这样:
var list = [];
async.each(data, function(elem, callback1) {
var classgene = '';
var custom_gene = { Name_Gene : elem['Name_Gene'] };
if (elem['Type_Gene'] == "reference") {
async.waterfall([
function(callback2) {
var id = elem['Id_Genes'];
geneModel.getGenesRefClass(id, function(error, data2){
if (error) return callback2(error);
classgene = data2[0]['Class_Name'];
custom_gene['classgene'] = classgene;
callback2(null, custom_gene);
});
},
], function(err, custom_gene) {
// If you want to propagate errors, uncomment the following:
// if (err) return callback1(err);
list.push(custom_gene);
console.log(list);
callback1();
});
} else {
callback1();
}
}, function(err){
// if any of the saves produced an error, err would equal that error
if (err) {
console.log('An error occurred!', err);
}
console.log(list);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.