Struggling to pass an array as a return value from a nested function

I'm seeking assistance with the code snippet below. I am encountering difficulties in accessing the "result" variable outside of the selectCb function scope. While "result" is properly assigned and functional within the selectCb scope, it becomes inaccessible beyond that boundary.

function queryDB(client, queryString) {

    result = ''; //initialize global variable

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

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

    });

    client.end();

    console.log(result['id']); //UNABLE TO FETCH - RETURNS UNDEFINED

    return result; //deliver complete result array

};

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

console.log(data['id']) //INACCESSIBLE RESULT - RETURNS UNDEFINED;

Answer №1

Ensure to pass a callback as an argument and invoke it once the data is available:

function fetchFromDB(connection, queryStr, callback) {
    connection.query(queryStr, function handleResults(error, results, fields) {
        if (results.length > 0) {
            callback(results[0]);
        }
    });
};

var result = fetchFromDB(connection,"select name from users", function (result) {
  console.log(result['name']);
});

Tools like async can simplify handling nested callbacks.

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

Generate a randomly structured 2D array called "Array" using JavaScript

Can anyone help me with extracting a random array from a 2D named array? I've tried several solutions but none of them seem to work. var sites = []; sites['apple'] = [ 'green' , 'red' , 'blue' ]; sites['o ...

Concealing the nearest object

I am currently working on using jquery to hide certain content on a website's index page. Within the fiddle, there is commented out code which I have been experimenting with - however, it hides all content divs if any toggle link is clicked. HTML & ...

Toggle the row to expand or collapse upon clicking it

After extensive research, I have been unable to get the row expansion and collapse feature to work in my script. Here is my current script: <thead> <tr> <th width="5" class="cb"><input type="checkbox" id="cbcall" /& ...

Creating a distinct header value for every $http request

I've been assigned the task of adding a unique ID for each request to all HTTP requests made by our AngularJS application for logging purposes. While this is more crucial for API calls, I'm currently working on implementing it for all kinds of re ...

A guide on accessing array values in MongoDB using Python syntax

Kindly, handle with care I have a mongo doc structured like this : { "Institute" : "Ucambridge", "Project" : [ #array of projects {"Sample":[ #array of samples { "workflow" : "abc", "owner" : "peter" } ...

Create an iterative process for manipulating JSON data and incorporating interactive buttons within a React application

Just starting out with React and encountered an issue with this code: class Tests extends React.Component { async getTests() { var url = "http://127.0.0.1:100/getTestList" var buttons=[]; const resp = await fetch(url); const data = awa ...

Using Angular: Dynamically load an external JavaScript file after the Component View has finished loading

In my Angular 5 application, I am faced with the challenge of loading a JavaScript script file dynamically after my component view has been fully loaded. This script is closely related to my component template, requiring the view to be loaded before it ca ...

Is there a way to tally the frequency of a specific property appearing in one array within another, and then transfer those matches into a separate array?

My goal is to match the fk_city with the $id of each city in the 'list_cities' array, and then calculate the number of occurrences. const list_cities = [ { $id: '15FG', name: 'Pittsburg' }, { $id: '50HS', name: & ...

When echoing SESSION in PHP, the previous value is displayed

<script language="javascript"> function handleEmergency() { if(document.getElementById('emer').checked == true) { <?php $_SESSION['total2']= $_SESSION['total1'] ...

Removing an element from a multidimensional associative array in PHP - a concise guide

I am dealing with a complex, associative array structure. My goal is to remove specific items from the array, regardless of their position. This array is specifically used for constructing the navigation menu on a website. Sub-items are always nested with ...

Manipulating Pixel Width and Height of Cells in Google Sheet using Apps Script

I'm looking for a solution to effectively retrieve and update the height and width in pixels of a Google Cell using Google Apps Script. While there is a built-in getWidth() function available, it only returns the width of the range in cells, which doe ...

Using AngularJS to dynamically assign classes with values derived from an ng-repeat loop

I'm attempting to assign a class to a table row using ng-class based on the value of ng-repeat. I have searched online and found examples that involve calling a function. Is it possible to simply set ng-class with a value instead of using a function? ...

Utilize the Spotify API to discover tracks by including the album title and artist's name in the search

Currently working on a project that involves searching for a music track on Spotify. The idea is to input the track name in the text area and generate a list of matching Track IDs along with Artist Names, Album Names, and Artwork. I have made some progress ...

Crop images in a canvas using a customized rectangle with the help of JQuery

I am trying to crop an image inside a Canvas element using a selection rectangle. My project utilizes jQuery and I am in search of a plugin that can help me implement this custom selection rectangle on the canvas itself, not just on images. Are there any ...

Is there a way to dynamically expand and collapse all table rows, with the latest row always remaining visible, using pure JavaScript?

I have a form input field where I enter data. The entered data is then displayed in a table as a new row, with the most recent entry at the top. What I want to achieve is to show only the newest row in the table and hide all other rows. When I hover over ...

Combining two arrays in Go results in a container assignment error

I've been troubleshooting my code all morning but can't seem to figure out what's wrong. The error message says it can't assign containers. Here's the playground link for you to check. Below is the problematic code: func My_Merg ...

I am struggling to get the pop-up to close using the current code. I suspect that the issue might be related to the variable I was previously using in WordPress. I have made changes but the pop-up

While delving deeper into the realm of Javascript, I encountered a stumbling block with a single popup intended for the main page of a WordPress website I am constructing. Despite my attempts to modify the code's variables, they seem unyielding. Surpr ...

Remove the name from the array before returning it from the method

Currently, I am working on an assignment that involves completing the code block provided below: public int[] test(String input) { return new int[1]; } So far, I have made progress in manipulating the string as required. However, when it comes to ret ...

What is the correct way to utilize Array.reduce with Typescript?

My current approach looks something like this: [].reduce<GenericType>( (acc, { value, status, time }) => { if (time) { return { ...acc, bestValue: valu ...

Angular JavaScript can be utilized for JSON date formatting

I am having trouble displaying JSON data in an HTML table. When I run my file, the date appears as '2018-11-21T00:00:00.000+0000' in the table. However, I only want to display '2018-11-21'. Can someone help me figure out how to split it ...