Implementing non-blocking asynchronous object return in a node.js function

Struggling with a function that accesses data from a JSON file and queries it for a specific key. Unfortunately, the return function seems to be executing before the query can find the key.

Even after querying and attempting to return the variable queryresponse within the query function, it consistently returns 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'));
// results in undefined.

Looking for a way to make this statement asynchronous. Any suggestions on how to achieve this?

I should mention that I also attempted the following code, but unfortunately, still getting 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'));

Appreciate any assistance you can offer!

Answer №1

To efficiently retrieve data from a database, utilize a callback function as shown below:

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

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

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

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

    console.log(result);
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Angular is having trouble with the toggle menu button in the Bootstrap template

I recently integrated this template into my Angular project, which you can view at [. I copied the entire template code into my home.component.html file; everything seems to be working fine as the CSS is loading correctly and the layout matches the origina ...

Synchronizing two navigation menus on a single-page application website

Let me start by saying that I specialize in back end development and am facing a specific challenge with building a website that includes two navigation menus. The main navigation menu features links like Home, while the sub-navigation menu includes option ...

Having trouble setting up the next-auth login page and experiencing issues with the getProviders() function

Greetings to all fellow web developers, I am currently working on a Next.js application that utilizes next-auth for user authentication. I have set up the [...nextauth].js file in the "pages/api/auth" directory and a signin.js file in the "pages/auth/" di ...

Error due to PlatformLocation's location dependency issue

My AppComponent relies on Location (from angular2/router) as a dependency. Within the AppComponent, I am using Location.path(). However, when running my Jasmine test, I encountered an error. Can you help me identify the issue with my Jasmine test and guide ...

What is a more effective way to showcase tab content than using an iframe?

I currently have a webpage set up with three tabs and an iframe that displays the content of the tab clicked. The source code for each tab's content is stored in separate HTML and CSS files. However, I've noticed that when a tab is clicked, the ...

Using the Jquery accordion function within google maps is limited to running only one time

After successfully creating a google maps page with markers generated from XML, I encountered an issue. The plan was to display event information in a div when a marker is clicked, along with attaching an accordion to the events data. Although the first cl ...

The absence of the iframe in ie8 is causing problems that cannot be fixed with relative positioning

On a website, I am integrating an external 2-factor authentication solution called Duo Web using their PHP and Javascript. It works smoothly on all browsers except for IE8. When the user passes the initial login screen, the 2FA login page loads, but the if ...

POST request body is not defined

Client Interface: procedure OnButtonClick(Sender: TObject); begin gcm := GetGCMInstance; p := TJavaObjectArray<JString>.Create(1); p.Items[0] := StringToJString('460004329921'); FRegistrationID := JStringToString(gcm.register(p)); ...

The cart total variable in Vuejs is coming back as NaN

I'm currently in the process of creating a cart system using vuejs and I've encountered an issue where my total variable is displaying NaN instead of calculating the total price of all products. Below is the function responsible for calculating ...

Is there a way to ensure an ajax call finishes executing without relying on 'async: false' or callbacks?

In my view, I have implemented a TypeScript code defining a KnockoutJS binding handler for a clickable element as shown below: module MyModule { export interface ICopyButtonParams { dataUrl: string; } ko.bindingHandlers.copyButton = { ...

automatic logout feature activates on simple-ember-auth/oauth2-server following a period of user inactivity

In my current setup, I have integrated simple-ember-auth on the front end and oauth2-server on the backend, utilizing password and refresh_token grants. As the authorization token approaches expiration (a server-defined time limit), simple-ember-auth promp ...

Creating nested tables by assigning unique Div IDs to each table element

Can we utilize a straightforward JavaScript/jQuery function to nest elements inside table elements? For instance, every square comes with its own unique ID (A1, B7, C5). How can I use this ID to insert the checker image in any selected tile upon clicking? ...

Bypass the typical practice of choosing input with javascript

I have a form with a select input that has a dropdown list of options. The requirement is that when the select input is clicked, I need to validate the form. If the form is incomplete, I want to prevent the select input from showing the option list. Howeve ...

Using JSON in an AJAX request to log in

Currently, I am in the process of developing a straightforward login form that utilizes AJAX for server communication and PHP as the server-side script. However, I have encountered some challenges while trying to send login data to the server via JSON. Th ...

Exclude JSON Property if it Lacks a Certain Value

I'm attempting to retrieve specific values from a DynamoDB database where the name is "john". The challenge I'm facing is that although I can fetch values containing name: john from a mapped list, I also receive additional unwanted values. When ...

Adding jQuery content to a div that is being created dynamically

Currently implementing a save/load feature using JSON for a diagram that utilizes jsPlumb. While the save functionality is working perfectly, the load functionality is encountering difficulties in replicating the full initial saved state. The issue arises ...

Encountering difficulties while trying to install ng2-material in Angular 2

I'm attempting to utilize a data table with the ng2-material library from ng2-material as shown below: <md-data-table [selectable]="true"> <thead> <tr md-data-table-header-selectable-row> <th class="md-text-cell">M ...

What steps can be taken to issue an alert when the table does not contain any records?

Upon clicking the submit button, the value from the database is retrieved based on the hidden field ID and displayed in a table. If the value is present, it should load in the table; otherwise, an alert saying 'there is no record' should be displ ...

MUI version 5 - Checkboxes are receiving a variety of unique classes

After recently upgrading from Mui v4 to v5, I've noticed a strange behavior with checkboxes. Upon inspecting the DOM differences between the two versions, it appears that some additional classes are now being applied in v5 and the extra span with the ...

JavaScript data manipulation: Determining percentage change within a nested JSON structure

Provided is a JSON file structured like this... data =[ { key: "london", values: [ {day: "2020-01-01", city: "london", value: 10}, {day: "2020-01-02", city: "london", value: 20}, {day: " ...