Is there a way to retrieve an array generated within a JavaScript loop?

I've been working on retrieving column values from a database and storing them in an array, but I keep getting an empty array as the result.

function FetchData(query, db) {
var resultArray = new Array();
db.transaction(function(tx) {
    tx.executeSql(query, [], function(tx, rs) {
        var length = rs.rows.length;

        for (var i = 0; i < length; i++) {
            var row = rs.rows.item(i);
            resultArray.push({latitude : row['latitude']});
        }
    });

});
return resultArray;
}

Even though I can see the array being populated inside the for loop, it ends up empty when returned.

Answer №1

Your code is utilizing asynchronous functions, meaning a direct return will not be effective. To handle this, you should implement a callback function.

function Select(query, db, callback) {
    var result = new Array();
    db.transaction(function(tx) {
        tx.executeSql(query, [], function(tx, rs) {
            var len = rs.rows.length;
            for (var i = 0; i < len; i++) {
                var row = rs.rows.item(i);
                result.push({latitude : row['latitude']});
            }
            callback(result);
        });
    });
}

Select(function(result) {
    // process the result here
})

Answer №2

From the details you provided, it appears that tx.executeSql operates asynchronously. In this scenario, your Select function should ideally utilize a Promise (alternatively known as a Future) to handle the outcome, or simply send the results back to the original caller.

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

Protractor's modal dialogue displays numerous outcomes when accessing ng-repeater elements

Trying to click on an element located within a repeater has presented some challenges. The issue arises from the fact that it is a modal dialog and returns multiple elements for the repeater. Each page in our application functions as a modal dialog, leadin ...

Using JavaScript to redirect browser with a specific string

My goal is to redirect all users who visit a specific URL to another page. While this redirection works effectively, I now need to implement it with a tracking URL. The issue arises when Javascript automatically adds a "/" in front of the tracking string ...

changing web pages into PDF format

I need to convert HTML to PDF on a Linux system and integrate this functionality into a web application. Can you suggest any tools that are capable of doing this? Are there any other tools I should consider for this task? So far, I have attempted the foll ...

A guide on navigating through nested JSON objects with the help of async.js

Having recently transitioned from a Python background to nodeJS/Javascript's asynchronous nature, I am exploring how to traverse a nested JSON object and extract its values using async.js. In my quest for answers, I stumbled upon this helpful snippet ...

Ways to extract innerHTML content from a loaded element generated by using the .load() method

Check out the code snippet below: template.html : <div id="nav"> Welcome to Space </div> layout.html : <div id="content"> </div> $('#content').load("template.html #nav"); ale ...

Database storage of image tags on websites, similar to functionality found on social media platforms such as Facebook

Looking for an image tagging solution for websites that can save tag data directly to a database instead of a local file? I've checked out , but it doesn't support database integration in the current version. Ideally, I need a solution that is co ...

"Exploring the use of conditional rendering in React to dynamically hide and show components based

I am currently immersed in the world of React/Redux, focusing on an e-commerce project. This particular application offers two payment methods: cash and card payments. On the product display page, both payment icons are visible. However, I am seeking a sol ...

Present location of current page

I utilize angularJS to create a web page with the utilization of ngView for a single page and multiview. Is there a way to display the current page's location, such as Home/abc/dcv? On this website https://docs.angularjs.org/guide/, the page location ...

Tips on running methods consecutively within ngOnInit in Angular

I'm currently working on an ngoninit function that contains four methods. Two of these methods are responsible for retrieving data from the API, while the other two are intended to load this data when the page loads. ngOnInit(){ getname(); getsubjects ...

Find the total duration of all items within an array by utilizing the Moment.js library

Within an array of objects, each object contains a field named "duration" that represents a string. Here is an example of one such object: { id: 14070 project: {id: 87, name: "Test project for time tracking"} issue: {id: 10940} user: {id ...

Guide on downloading jsreport in .Net using C# without opening it

I am using JS Report to generate a file and save it in the root directory. However, I want the file to be downloaded directly instead of opening for viewing. var header = await _jsReportMVCService.RenderViewToStringAsync(HttpContext, RouteData, "H ...

ES6 does not work with React hello world

Can anyone help me with troubleshooting my code? I've checked the console on jsbin and can't find any errors. http://jsbin.com/susumidode/edit?js,console,output Class secondComponenent extends React.Component { render(){ return ( &l ...

Access a portion of a file located on a distant server

Is it possible to read part of a remote file using Ajax without relying on server-side technologies like PHP? I believe the HTTP Range header could be utilized for this purpose, but how can we set it with Ajax? Can we even set HTTP headers in Ajax request ...

Is there a way to switch tabs through programming?

Is there a way to switch between tabs using jQuery or JavaScript when using the tabbed content from ? I have tried using $("tab1").click(); I have created a fiddle for this specific issue which can be found at: https://jsfiddle.net/6e3y9663/1/ ...

What is the best way to manage the back button functionality on pages that use templates?

I am currently developing a website using angularjs. The layout consists of two main sections: the menu and the content area. For instance This is an example page: /mainpage <div> <div id="menu"> <div ng-click="setTemplate('fi ...

Uncovering the issue with decoding JSON in GO Lang (failure to parse a simple array)

Working with structs and JSON in Go can be a bit tricky. I recently encountered an issue where my struct was not picking up an array from the parsed JSON data. Everything else seemed to work fine, but the array was empty. If anyone has any insights on wh ...

"Make sure to always check for the 'hook' before running any tests - if there's an issue, be sure

before(function (func: (...args: any[]) => any) { app = express(); // setting up the environment sandbox = sinon.createSandbox(); // stubbing sandbox.stub(app, "post").callsFake(() => { return Promise.resolve("send a post"); }); ...

Unlocking numerical input solely by executing the specified command within the most up-to-date iteration of the Chrome Extension of Selenium IDE

After executing the command in Selenium IDE, I successfully extracted the sentence, "Your booking ID is 1234", and saved it in a variable named myText. <table> <tr> <th>Command</th> <th>Target</th> < ...

I am encountering undefined values when utilizing momentjs within Angular

My project is utilizing angular and momentJS, with the addition of the angular-moment library. You can find my current progress in this fiddle However, I am encountering an error when trying to use moment in a controller method: TypeError: undefined is n ...

In the world of programming, there exists a mysterious creature known as

I've been experimenting with different methods, but nothing seems to be working for me. What I am attempting to accomplish is <?php $php_var = a-thing; echo ' <script text/JavaScript> document.cookie = "arrayid"+&apos ...