0

I am using a function that accesses data from a JSON file, then queries that file for a specific key. Im attempting to return its findings but it appears that the return function is being executed before the query finds the key.

After the query i return the variable queryresponse in the query function, it always ends up coming back undefined.

var jsonQuery = require('json-query');
var fs = require('fs');

function querydb(netdomain){
fs.readFile('./querykeys.json', 'utf8', function (err, data) {
    if (err){console.log('error');} 
    var obj = JSON.parse(data);
    var queryobject = netdomain.toString();
    var queryresponse =  jsonQuery('servers[netshare=' + queryobject + '].netdomain', {
          data: obj
        });
    return queryresponse;



});

}

console.log(querydb('timeline'));
// returns undefined.

What can i do to make this statement asynchronous?

Id like to notate that i have also tried this, also does not function, still gives undefined responses.

var jsonQuery = require('json-query');
var fs = require('fs');

function querydb(netdomain){
fs.readFile('./querykeys.json', 'utf8', function (err, data) {
    if (err){console.log('error');} 
    var obj = JSON.parse(data);
    var queryobject = netdomain.toString();
    return  jsonQuery('servers[netshare=' + queryobject + '].netdomain', {
          data: obj
        });




});

}

console.log(querydb('timeline'));

Thank you for any help you can provide

Christopher Allen
  • 7,769
  • 5
  • 20
  • 35
  • I think u have to return jsonQuery().value – Abdul Rehman Sayed Jul 16 '16 at 07:23
  • Your function already is asynchronous. You need to study the difference between synchronous and asynchronous. What you are asking for is a synchronous result, which you cannot get from an asynchronous function. Read the duplicate question for all your options. You can't directly return a value from an asynchronous operation. You have to use a callback, a promise or some other similar technique so you can be notified later when the value is ready. – jfriend00 Jul 16 '16 at 07:49

1 Answers1

0

You need to use a callback. Something like this:

var jsonQuery = require('json-query');
var fs = require('fs');

function querydb(netdomain, callback) {
    fs.readFile('./querykeys.json', 'utf8', function (err, data) {
        if (err) {
            callback(err);
            return;
        }

        var obj = JSON.parse(data);
        var queryobject = netdomain.toString();
        callback(null, jsonQuery('servers[netshare=' + queryobject + '].netdomain', {
              data: obj
        }));
    });
}

querydb('timeline', function (err, result) {
    if (err) {
        console.log('ERROR: ' + err);
        return;
    }

    console.log(result);
});
user94559
  • 59,196
  • 6
  • 103
  • 103