It is possible an synchronous mysql query in nodej

2019-09-15 12:00发布

问题:

I try find solutions like "Promices" or modules like "synchronize" or "sync", but I donsen't fine a properly solution ):

The way its I have like 10 tables 'user', 'data', 'game'. And functions like:

getUsers(){}       // UserTable
getData(){}        // DataModel
getGames(){}       // GameTable
getUserByGames(){} // UserModel

And some funtions have needs to return me a model or table... and in some cases I need that model or that 'answer' to make another query and another stuff.

So, i need to do synchronous querys to make that in the best way, no use '.then' or stuff like that :/

Did you know how I can doit in nodejs?

(Maybe a solution can be put a flag in true each async function and in the callback change the flag to false. With a while for dosent end the original function?)

回答1:

You can mix callbacks, sequential and parallel execution, loops, recursion with SynJS. Here is an example to illustrate:

var SynJS = require('synjs');
var mysql      = require('mysql');
var connection = mysql.createConnection({
  host     : 'localhost',
  user     : 'tracker',
  password : 'tracker123',
  database : 'tracker'
});

function runSQLQuery(modules,connection,context,query,queryParams) {
    var res = {done: false};
    connection.query(query,queryParams, function(err, rows, fields) {
          res.err = err;
          res.rows = rows;
          res.done = true;
          //console.log('got rows:',rows);
          modules.SynJS.resume(context);
    });
    return res;
}

function myFunc(modules,connection) {
    for(var i=0; i<3; i++) {
        console.log('Iteration:',i);
        // sequential execution
        var res1 = modules.runSQLQuery(modules,connection,_synjsContext,"SELECT 100+? as id",[i]);
        SynJS.wait(res1.done);
        console.log("res1=", res1.rows);

        var res2 = modules.runSQLQuery(modules,connection,_synjsContext,"SELECT 200+? as id",[i]);
        SynJS.wait(res2.done);
        console.log("res2=", res2.rows);

        // parallel execution
        var res3 = modules.runSQLQuery(modules,connection,_synjsContext,"SELECT 300+? as id",[i]);
        var res4 = modules.runSQLQuery(modules,connection,_synjsContext,"SELECT 400+? as id",[i]);
        SynJS.wait(res3.done && res4.done);
        console.log("res3,4=", res3.rows, res4.rows);
    }
};

var modules = {
        SynJS:  SynJS,
        mysql:  mysql,
        runSQLQuery: runSQLQuery,
};

SynJS.run(myFunc,null,modules,connection,function () {
    console.log('done');
    connection.end();
});

It produces following output:

Iteration: 0
res1= [ { id: 100 } ]
res2= [ { id: 200 } ]
res3,4= [ { id: 300 } ] [ { id: 400 } ]
Iteration: 1
res1= [ { id: 101 } ]
res2= [ { id: 201 } ]
res3,4= [ { id: 301 } ] [ { id: 401 } ]
Iteration: 2
res1= [ { id: 102 } ]
res2= [ { id: 202 } ]
res3,4= [ { id: 302 } ] [ { id: 402 } ]
done