Wednesday, 3 May 2017

node.js async/sync with For Loop, Query, and Additional function

Hello I am having an issue with the following sequence, I need to run multiple queries which build on each other that are in a for loop then once the final result is obtained to implement the result. I am having an issue where my for loop is looping past the query, also I need to stop the code while the findX function is running.

I know this is an async problem but I don't see how I could chain promises, or use the async npm package with needing to loop queries that depend on the result of the previous query. Thanks in advance.

    function findX(){
      //executes another query
    }

function solve(res, connection, info, requestArr, callback){

        var parentID = null;
        var obj = {};

        for (var i = 0; i <= requestArr.length; i++) {

          connection.query("SELECT WHERE ", [parentID, requestArr[i]], function(err, results) {
            if(results[0]['x']){
              var obj =  findX(x)
              break;
            }else{
                 parentID = results[0]['parentID'];
            }
          });
        }

    //Do stuff with obj only after the final result has been set in the for loop
      }



via Grant Weiss

No comments:

Post a Comment