I want Nodejs to repeat MySQL query statements synchronously

Asked 1 years ago, Updated 1 years ago, 349 views

I am currently studying Javascript using Nodejs.
I would like to store the values obtained by executing the query statement in an array, but it will become asynchronous, so it will not store data after the second week repeatedly.
Each record in DB has a parent_id column (which contains the parent record id), and may have multiple child records.

I would like to obtain all the terminal child element id from the id(req.body.id) I received from Main.js and store it in idArray without duplication.
Please let me know what kind of code I should write.

let resultTmp=0;// Repeated decision element
let parentIdArray=[]; // Array containing parent elements (forEach)

parentIdArray.push(req.body.id); // Store values from Main.js in post

while(resultTmp.length!==0){
  parentIdArray.forEach(parentId)=>{
    connection.query(
      'SELECT id, folder_name, parent_id FROM folder WHERE parent_id=?',
      [parentId],
      (error, results) = > {
        results.forEach(result)=>{
          // Add if not duplicated
          if(idArray.indexOf(result.id)==-1){
            idArray.push (result.id);
          } // Add if not duplicated
          if(parentIdArray.indexOf(result.id)==-1){
            parentIdArray.push(result.id);
          }
        });
        // If results are empty, the While statement ends.
        resultTmp = results;
      }
    );
    // Delete array elements once executed in parentIdArray.forEach
    parentIdArray.splice(parentIdArray.indexOf(parentId), 1);
  });
}
res.send({response:idArray});

javascript mysql nodejs

2022-12-11 05:50

1 Answers

This time, I was able to do the following without using Promise, so I would like to solve it myself.

connection.query('select * from folder', (error, results)=>{
        console.log(results);
         while(resultTmp.length!==0){
          parentIdArray.forEach(parentId)=>{
            results.forEach(result)=>{
              if(parentId==result.parent_id){
                console.log(`id:${result.id}`);
                // Store if not duplicated
                if(idArray.indexOf(result.id)==-1){
                  idArray.push (result.id);
                }
                if(parentIdArray.indexOf(result.id)==-1){
                  parentIdArray.push(result.id);
                }
              }
            });
            parentIdArray.splice(parentIdArray.indexOf(parentId), 1);
          });
        }
        res.send({response:idArray});
      });


2022-12-11 16:58

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.