-4

I am using Angular,NodeJS, MYSql

i need to get the return values of the mysql query in other function. is that posible

as like the following code

i need to get the details from the query from other function, but i cannot able to get the details of user address.

any solution for get the details?

thank you

exports.getUserDetails= (req, res) => {
    sql = 'SELECT * FROM users ';
    connection.query(sql, (error, results, fileds) => {
        if(error) {
            res.send({
                "success" : false,
                "message" : "Error : "+error.message
            });
        }
        else {
            if(results.length >0) { 
                let users = [];
                results.forEach(user => {
                    let addressDetas = this.getUserAddress(user.id);
                    let userdata = {}
                    userdata = user;
                    userdata.address = addressDetas; 
                    users.push(userdata);
                });
                res.send({
                    "success" : true,
                    "message" : "No Record ",
                "result" : users
                });
            }
            else {
                res.send({
                    "success" : true,
                    "message" : "No Record ",
                    "result" : results
                });
            }
        }
    });
}

exports.getUserAddress= (userid) => {
sql = 'SELECT * FROM address WHERE user_id = "'+userid+'" ';
    connection.query(sql, (error, results, fileds) => {
        if(error) {
            return error;
        }
        else {
            return results;
        }
    });
}
Ed Bangga
  • 12,879
  • 4
  • 16
  • 30
  • 3
    You might consider using consistent indentation when writing code - it'll make reading and debugging it much easier, not only for potential answerers, but for you as well, when we can all see the `{` `}` blocks and their nesting level at a glance, rather than having to carefully pick through each line just to pick up on the logical paths. – CertainPerformance Jul 05 '19 at 07:34

1 Answers1

0

It's not getUserAddress that is returning, it's the callback passed in to connection.query. if you want to capture the results of the query, you need to pass in your own callback function (conventionally as the last argument) to getUserAddress. However, there have been significant syntax features to help you write the code in more synchronous looking style, notably Promise and the async and await keywords. If you rewrite your function using these, you will be able to use it as you intend. Something like:

const until = require ('util'):

exports.getUserAddress = async function (userId) {
  const SQL = select etc....'';
  const query = until.promisify(connection.query);
  return await query(sql,);
}

And use it like this:

async function printAddress() {
  const address =await getUserAddress(123);
  console.log(address);
}
Will Munn
  • 7,363
  • 4
  • 27
  • 32