Search code examples
mysqlnode.jsnode-mysql

node mysql sequential query execution


I am trying to fetch some results and do the further processing based on those results, but I can't proceed to work it sequentially,

var sql = query1;

    con.query(sql, function (err, results) {
      if (err) throw err;
     //  ids => 5,2,3,4
      for (i = 0; i < results.length; i++) {

        target_user = results[i].ID

        var sql = "DELETE QUERY";

        con.query(sql, function (err) {
          if (err) throw err;
          console.log(target_user)

          var sql = "INSERT QUERY";
          console.log(sql)
          con.query(sql, function (err) {
            if (err) throw err;

          })
        })


      }
    })

The above code runs asynchronously, What I expect is an output in a loop like this

// "DELETE QUERY";
//5
// "INSERT QUERY";
// "DELETE QUERY";
//2
// "INSERT QUERY";

and so on..

but what I get is

// "DELETE QUERY";
//5
// "DELETE QUERY";
//5 //not fetching the next array val
// "INSERT QUERY";
// "INSERT QUERY";

Any help is much appriciated.


EDIT

from answers I updated code like this

now the code looks like this

 aysnc.forEach(results, function(elem, callback){
target_user = elem.id
   console.log('out')
                    console.log(target_user)
                    con.query(sql, function (err) {
                      if (err) throw err;
                      console.log('in')
                    console.log(target_user)
})
})

A strange thing happened that output is

out
5
in
5
out
2
in
5 //when it is supposed to be 2

Solution

  • You could use recursion to solve something like this. Keep calling function until there is no elements left in results

    con.query(sql, function (err, results) {
      if (err) throw err;
      deleteAndInsertResults(results);
    })
    
    function deleteAndInsertResult(results)
    {
        target_user = results[0].ID
    
        var sql = "DELETE QUERY";
    
        con.query(sql, function (err) {
          if (err) throw err;
          console.log(target_user)
    
          var sql = "INSERT QUERY";
          console.log(sql)
          con.query(sql, function (err) {
            if (err) throw err;
            results.shift();
            if(results.length){
              return deleteAndInsertResult(results);
            }
    
          })
        })
    }