[英]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.