node.js - Confusing with call back in node js -


i have query in nodejs. please modify code such way query database each iteration , store each time result in result array. , send callback function after loop execution finished.when trying place callback(result) after result.push(data) works send rows.length times because of loop.

function query_database(req,callback){ result=[];

class_code=req.body.class; branch=req.body.branch; year=req.body.year; start_date=req.body.start_date; end_date=req.body.end_date; flag=false; query='select id,rollno student branch="'+branch+'" , class="'+class_code+'" , year="'+year+'"';  //console.log(query); connection.query(query, function(err, rows, fields) {     if (!err){         query_total_working_days(start_date,end_date,branch,class_code,year,function(err,data){             if(err){              }             else{                 total_days=data;                 for(index=0;index<rows.length;index++){                     query_attendance(rows[index].id,rows[index].rollno,start_date,end_date,total_days,function(err,data){                         if(err){                          }                         else{                             result.push(data)                         }                     });                 }              }         })         callback(null,result)      }      else         console.log('error while performing query.'); }); 

}

your code maybe simplify this:

function query_database(callback) {   let result = [];   query_all(function(rows) {     (let = 0; < rows.length; i++) {       query_row(rows[i], function (data) {         result.push(data); // (2)       });      }   })   callback(result); // (1) } 

the problem can't sure (2) finished before (1). actually, (1) called before (2) can called.

to make correct, need change following code:

function querydatabase(callback) {   let result = [];   queryall(function(rows) {     let = 0;     let rowcallback = function (data) {       result.push(data);       i++;       if (i == rows.length) {         callback(result);             } else {          queryrow(row[i], rowcallback);       }     };      queryrow(row[i], rowcallback);   })   callback(result); // (1) } 

Comments

Popular posts from this blog

Command prompt result in label. Python 2.7 -

javascript - How do I use URL parameters to change link href on page? -

amazon web services - AWS Route53 Trying To Get Site To Resolve To www -