0

Please help with the below code. I am having trouble returning the "result" variable within the selectCb function. "result" is assigned and works fine within the selectCb scope, however outside the scope I cannot access it.

function queryDB(client,queryString) {

    result = ''; //declare global variable

    client.query(queryString, function selectCb(error, results, fields) {

      if (results.length > 0) result = results[0]; 
          console.log(result['id']); //WORKS HERE

    });

    client.end();

    console.log(result['id']); //DOES NOT WORK - UNDEFINED

    return result; //return result array

};

var data = queryDB(client,"select id from table");

console.log(data['id']) //DOES NOT WORK - UNDEFINED;
0

1 Answer 1

1

You'll need to take a callback as a parameter, and call it when you have the data:

function queryDB(client, queryString, callback) {
    client.query(queryString, function selectCb(error, results, fields) {
        if (results.length > 0) {
            callback(results[0]);
        }
    });
};

var data = queryDB(client,"select id from table", function (data) {
  console.log(data['id']);
});

Libraries such as async can help when the callbacks become too nested.

Sign up to request clarification or add additional context in comments.

1 Comment

var data = queryDB(client,"select id from table", function (data) {console.log(data['id']); }); console.log(data['id']); //would this then work?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.