0

I have a question about asynchronous function. Here my function "My_function":

 function My_function (my_name, callback){
      stmt = db.prepare ("SELECT number_table1 from my_table1 WHERE user=?");
        stmt.bind(my_name);
        stmt.get(function(error,row){
          if(error){
            throw err;
          }
          else{
            if(row){
              callback(number_table1);
            }
            else{
              console.log("error");
            }
           }
       });
    }

Work fine but I have 2 tables and I need do other query and I need add two numbers so... in my function I need do too this query:

stmt = db.prepare ("SELECT number_table2 from my_table2 WHERE user=?");

and finally return back in my callback "number_table1 + number_table2". Somebody know how to solve it? Thanks in advance.

Best regards!

Tecnico
  • 449
  • 2
  • 6
  • 17

3 Answers3

0

In cases like your's I like to use the async module, because the code will be more legible. Example:

var async = require('async');

function My_function(my_name, callback) {
  var stmt = db.prepare("SELECT number_table1 from my_table1 WHERE user=?");
  stmt.bind(my_name);
  stmt.get(function (error, row) {
    if (error) {
      callback(error, null);
    } else {
      if (row) {
        callback(null, number_table1);
      } else {
        callback(new Error("row not found"), null);
      }
    }
  });
}

//if you need the results in a specific order, you can use "series" instead of "parallel".
async.parallel(
  //array of functions
  [
    function (callback) {
      My_function('firstName', callback);
    },
    function (callback) {
      My_function('secondName', callback);
    }
  ],

  //results when all functions ends
  //the results array will equal [number_table1, number_table2], but the order can be different, because of the parallelism
  function (err, results) {
    if (err) {
      //handle the err 
    } else {
      //do something
    }
  }
);

Docs:

Victor
  • 5,043
  • 3
  • 41
  • 55
  • Thanks for reply me Victor but I need correct order in my datas because I need to do more complex operations :S – Tecnico Nov 04 '16 at 09:26
0

You need to synchronize the functions so that you can be sure both their results are ready before calling back. You can do this using promises: https://www.promisejs.org/

  • Make two regular functions (no callbacks), one for each query (function1, function2)
  • Make both return a promise
  • Then you can do

    function My_function(my_name) {
        var value1;
        function1(my_name)
            .then(function(resultFromFunction1) {
                value1 = resultFromFunction1;
                return function2(my_name);
            })
            .then(function(resultFromFunction2) {
                var result = value1 + resultFromFunction2;
                return result;
            });
        }
    }
    

Make sure to catch errors and handle different outcomes, what I presented is its simplest form.

Update

Here is an example of a function doing a query and returning a promise

function1 = function(user) {
    return new Promise(function (resolve, reject) {

        pool.getConnection(function (err, connection) {
            if(err) {
                reject ({status : false, message : "Error in connection database"});
            } else {
                connection.query('SELECT number_table1 from my_table1 WHERE user=?', [user], function(err, rows){
                    connection.release();
                    if(!err) {
                        resolve ({status: true, message: rows});
                    } else {
                        reject ({status: false, message: err});
                    }
                });
            }
        });
    });
}
Aidin
  • 1,230
  • 2
  • 11
  • 16
  • Aidin, thanks for reply me but, I'm new using asynchronous programming and do not understand too well. I'm not sure how to return a promise from my function. If you don't mind could you please write how would it be all the code? For return a promise in my function will be like this: function function1() { return new Promise( function (resolve, reject) { ... resolve(result); }); } Thanks in advane!! :) – Tecnico Nov 04 '16 at 09:22
  • @Tecnico I am quite new to but here is an example of how I do it. I am sorry but at the moment I cannot give a better example. Anyone who knows of a more relevant example is free to edit. – Aidin Nov 04 '16 at 09:36
  • @Tecnico I asked a promise question recently myself because I did not know how to do it. You can read it here. The answer is really good so maybe you can get something from it as well. http://stackoverflow.com/questions/39691647/nodejs-express-and-promises-not-doing-what-i-expect – Aidin Nov 04 '16 at 09:47
  • OK! Thanks you very much I will see your post. Other question, could you please check the function "My_function"? Is possible that something is wrong? – Tecnico Nov 04 '16 at 10:21
  • @Tecnico Sorry, I am not very familiar with that kind of writing. But I see something weird, `callback(number_table1);`. What is `number_table1`? It is not defined anywhere. Did you mean to return `row`? – Aidin Nov 04 '16 at 10:26
  • @Tecnico or do you mean the `My_function`in my code? – Aidin Nov 04 '16 at 10:29
  • @Tecnico There was a `;` in my code before the second `.then` which should not have been there – Aidin Nov 04 '16 at 10:32
-1

Make the table names function parameters. Convert that function to use async/await or promise. Use Promise.all to run both queries.

Jason Livesay
  • 6,317
  • 3
  • 25
  • 31