简体   繁体   中英

synchronous for in loop in node.js

I am working in node.js web application with express frame work and I need to get result form mysql database. I want to get result in synchronous. It is possible. Please suggest. For Example:

result = [{id:4,is_parallel:'No',name:'Pankaj'},{id:5,is_parallel:'Yes',name:'uu'},{id:6,is_parallel:'No',name:'kk'}]
for(val in result){
                       if(result[val].is_parallel=='No'){
                         var parallelArray = {};
                         parallelArray.id =  result[val].id;
                         parallelArray.name =  result[val].name;
                         newArray.push(parallelArray);
                            console.log(newArray); 
                     }else{
                    $sql  ='select id,process_wf_id from process_workflow_parallel_branch where process_wf_id='+result[val].id+''; 
                            connection.query($sql, 
                            function(err, results) {         
                            if(err){
                             callback(err,null);
                             }else{
                                 if(results.length>0){      
                                        for(val in results){
                                            //

                                        }   
                                    }
                             }


                            });

                        }

                     }  

As far as you use connection.query it is not possible to receive the result synchronously, for that function is asynchronous and you cannot avoid it of force it to be synchronous. Moreover, rely on asynchrony where possible is the way to go, for the risk is to incurr in blocking operations otherwise (as an example, writeFileSync ), and this is simply against what node.js is meant for.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM